Add validator for min age from a date object

This commit is contained in:
Kimmo Puputti 2017-10-05 16:00:48 +03:00
parent e2a2fb5a7b
commit 33f50aacce
2 changed files with 11 additions and 1 deletions

View file

@ -8,6 +8,8 @@ const formName = 'Styleguide.BirthdayInput.Form';
const FormComponent = () => {
const required = validators.required('A valid date is required');
const minAge = 18;
const minAgeRequired = validators.ageAtLeast(`Age should be at least ${minAge}`, minAge);
return (
<form>
<BirthdayInputField
@ -15,7 +17,7 @@ const FormComponent = () => {
name="birthday"
label="Date of birth"
format={null}
validate={required}
validate={[required, minAgeRequired]}
/>
</form>
);

View file

@ -1,3 +1,4 @@
import moment from 'moment';
import { types } from 'sharetribe-sdk';
const { LatLng } = types;
@ -68,3 +69,10 @@ export const emailFormatValid = message =>
value => {
return value && EMAIL_RE.test(value) ? VALID : message;
};
export const ageAtLeast = (message, minYears) =>
value => {
const now = moment();
const ageInYears = now.diff(moment(value), 'years', true);
return value && value instanceof Date && ageInYears >= minYears ? VALID : message;
};