Home > Software engineering >  Custom validation for different max date values in yup form
Custom validation for different max date values in yup form

Time:10-04

Is it possible using Yup validaion to have two different max conditions for one validation object? So currently I have this code:

yup.array().of(yup.object().shape({
                        dateToCheck: yup
                            .date()
                            .min(minDatetoCheck, 'Cant be below this date')
                            .max(maxDatetoCheck, 'Cant be above this date'))
                            .required()
                    })
                )
                .when('initialValue', {
                    is: true,
                    then: yup.array().min(1)
                })

So I wanted to add extra check so that any date that input with year above 9999 (so like years with 5 numbers and more) should be treated as 'Invalid date format' . I tried this:

        .date()
        .min(minDatetoCheck, 'Cant be below this date')
        .max(maxDatetoCheck, 'Cant be above this date')
        .max(9999, 'Invalid date format')
        .required()

However it is not working. Maybe is there a way to setup specific custom date form in .date() method that is adhering to 4 number long years only? Because the default year format allows for 5 number year long years and it is not something I need.

CodePudding user response:

You can use test method for that in yup:

    .test(
      'format',
      'our Date',
      date => date.getFullYear() <= 9999
    )

CodePudding user response:

Keyword of the problem is test

Here is the usage example of your case. I left last one. Because I don't understand the logic of invalid date case (9999). With test method you can make much more specific operations on your validation field. Also you can chain them. And remember it must be return boolean.

Code:

yup.array().of(yup.object().shape({
    dateToCheck: yup.date()
        .test(
            'cant-below-this-date',
            'Cant be below this date',
            (date) => {
                return minDatetoCheck < date;
            })
        .test('cant-above-this-date',
            'Cant be above this date',
            (date) => {
                return maxDatetoCheck > date;
            })
        .test('invalid-date',
            'Invalid date format',
            (date) => {
                // 9999 case goes here
                // You must return true if expression meet requirements otherwise you have to return false.
                // For dispatch validation error.
            })
        .required()
}))
    .when('initialValue', {
        is: true,
        then: yup.array().min(1)
    })

  • Related