From 33f50aaccee4e0e924f9bd23d1940f9f135c6dde Mon Sep 17 00:00:00 2001 From: Kimmo Puputti Date: Thu, 5 Oct 2017 16:00:48 +0300 Subject: [PATCH] Add validator for min age from a date object --- .../BirthdayInputField/BirthdayInputField.example.js | 4 +++- src/util/validators.js | 8 ++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/src/components/BirthdayInputField/BirthdayInputField.example.js b/src/components/BirthdayInputField/BirthdayInputField.example.js index 13a989cf..c82ff930 100644 --- a/src/components/BirthdayInputField/BirthdayInputField.example.js +++ b/src/components/BirthdayInputField/BirthdayInputField.example.js @@ -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 (
{ name="birthday" label="Date of birth" format={null} - validate={required} + validate={[required, minAgeRequired]} /> ); diff --git a/src/util/validators.js b/src/util/validators.js index 0e916365..9fedaaa9 100644 --- a/src/util/validators.js +++ b/src/util/validators.js @@ -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; + };