GitHub - jquense/yup: Dead simple Object schema validation
import * as yup from 'yup'
import moment from 'moment'
//after today
const dateTestAfterToday = function (value) {
const now = moment(Date.now()).format('YYYY-MM-DD')
if (moment(value).valueOf() <= moment(now).valueOf()) {
return false
} else {
return true
}
}
//after other day
const dateTestAfterOtherDay = function (field) {
return function (value, context) {
if (context.parent[field] && moment(value).valueOf() <= moment(context.parent[field]).valueOf()) {
return false
} else {
return true
}
}
}
//before other day
const dateTestBeforeOtherDay = function (field) {
return function (value, context) {
if (context.parent[field] && moment(value).valueOf() >= moment(context.parent[field]).valueOf()) {
return false
} else {
return true
}
}
}
const getValidationSchema = () => {
const requireMsg = 'This is a required field';
const dateTestAfterTodayMsg = 'Please select a date after today';
const dateTestAfterOtherDayMsg = 'Please select a date after the start date';
const dateTestBeforeOtherDayMsg = 'Please select a date before the end date';
const validationSchema = yup.object({
costStopDate: yup
.string()
.trim()
.required(requireMsg)
.test('costStopDate', dateTestAfterTodayMsg, dateTestAfterToday)
.test(
'costStopDate',
dateTestAfterOtherDayMsg,
dateTestAfterOtherDay('costStartDate')
),
costStartDate: yup
.string()
.trim()
.required(requireMsg)
.test(
'costStartDate',
dateTestBeforeOtherDayMsg,
dateTestBeforeOtherDay('costStopDate')
),
});
return validationSchema;
};