For ensuring that users are above 18 years old, I rely on the functionality provided by moment.js
.
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;
};
This function handles the validation of a user's age based on their birthdate. To implement this in a component, simply import and use the function. If no errors are returned, the user is confirmed to be over 18 years old; otherwise, an error message will be generated.
EDIT: Implementation involves creating a utils folder with a file named validateAge.js containing the aforementioned code snippet. Then, within the form where age verification is required, import the function as follows:
import { isOverEighteen } from 'here-goes-your-path/utils/validateAge';
To assign errors for the dateOfBirth field (or any relevant property), utilize the function in this manner:
errors.dateOfBirth = isOverEighteen(values.dateOfBirth);