I'm currently using Formik and validating with Yup.
I am looking to validate 2 dates, a start date, and an end date.
This was quite simple at first, I had two input fields, start_date
and end_date
. Both of these were just text inputs which accepted the following format, MM-YYYY
. The validation is good enough, it first turns that string into a date, using moment(value, "MM-YYYY")
.
From this, we then had the following tests:
start_date: Yup.string()
.test(
'test1',
'Format must be MM-YYYY',
function (value){
return moment(value, "MM-YYYY", true).isValid()
}
)
.test(
'test2',
'Start date must be before end date',
function(value){
let { end_date } = this.parent;
return moment(value, "MM-YYYY").isBefore(moment(end_date, "MM-YYYY"))
}
)
test1
simply checks that the MM-YYYY
is a valid date. test2
checks that the start_date
is before the end_date
. For the sake of simplicity, the end_date
tests are the same, except there is any extra test. The extra test checks that the end_date
is equal to or less than the current date.
That is what I currently have, however what I want is 4 input boxes:
start_date_month
(01, 02, 03...)start_date_year
(2000, 2001...)end_date_month
end_date_year
This is easy to do, but the tests will work a bit different, I'm not sure if we can test start_date_month
and start_date_year
together. In essence I need to concatinate them with -
to create MM-YYYY
again.
Any ideas how to do this with Yup?