简体   繁体   中英

Add validate birthday using validate.js to react project

I have read this article and used it in my app, article link

I would like to add a date validate to see if person is over 18

And I'm having difficulty to understand how and where to implement the parse and format methods that validate.js demands. I'm using react native and implemented the rest of the validation as it says in the article.

I use moment.js for birthday validation

import moment from 'moment';

export const isOverEighteen = (date) => {
  var eighteenYearsAgo = moment().subtract(18, "years");
  var birthday = moment(date);

  if (!birthday.isValid()) {
    return "invalid date";
  }
  else if (!eighteenYearsAgo.isAfter(birthday)) {
    return "To successfully open an account you have to be at least 18 years old.";
  }

  return;
};

That's a function that i made for birthday validation, and to use it in some component, just import it and use. If no errors is returned then user is above 18y old, else it will return some error in that return statements.

EDIT : I use it like this. creted utils folder and inside validateAge.js (inside is that code above) and in form where you validate age u can import that function

import { isOverEighteen } from 'here-goes-your-path/utils/validateAge';

and use like this to set errors for dateOfBirth (in my case that is name of property)

errors.dateOfBirth = isOverEighteen(values.dateOfBirth);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM