I have a validation schema for my Formik Form on React Native using Yup
. There are two fields (start_time
and end_time
) and i want to compare if start_time
is after end_time
and thrown a message to user.
I read about mixed.when
and tried to figure out a solution with that, but i'm blocked with it.
const isSameOrAfterTime = (startTime, endTime) =>
moment(startTime, HOUR_MINUTE_SECONDS_MASK).isSameOrAfter(endTime);
// example - data
// start_time: 08:00:25
// end_time: 10:23:42
start_time: Yup.string().when(['start_time', 'end_time'], {
is: (startTime, endTime) => isSameOrAfterTime(startTime, endTime),
then: Yup.string() // ???
otherwise: // ????
}),
I want to thrown a message when the start_time is after end_time
Use yup.test
instead.
https://github.com/jquense/yup#mixedtestname-string-message-string--function-test-function-schema
const SignupSchema = Yup.object().shape({
// (end_time, screma, self)
start_time: Yup.string()
.test(
'not empty',
'Start time cant be empty',
function(value) {
return !!value;
}
)
.test(
"start_time_test",
"Start time must be before end time",
function(value) {
const { end_time } = this.parent;
return isSameOrBefore(value, end_time);
}
),
end_time: Yup.string()
});
const isSameOrBefore = (startTime, endTime) => {
return moment(startTime, 'HH:mm').isSameOrBefore(moment(endTime, 'HH:mm'));
}