Home > Enterprise >  Yup date validation
Yup date validation

Time:11-16

I have 2 date fields and i want to validate the start date should be earlier than the end date. The logic I have validates this correctly but the only issue is i can select the same date and time for both start and end dates and it will not show any error. How can i modify the following in to check for equal start date and end date?

const licenseSchema = Yup.object().shape<ObjectSchemaDefinition<FormData>>({
  licenseStart: Yup.date(),
  licenseEnd: Yup.date().when('licenseStart', {
    is: (start) => start != null,
    then: (end) =>
      end.min(
        Yup.ref('licenseStart'),
        'License end date cannot be before start date',
      ),
  }),
});

my fields

<Field name="licenseStart" label="From" as={DateTimeTextField} />
<Field name="licenseEnd" label="To" as={DateTimeTextField} />

CodePudding user response:

Update your schema as below. Tested in local repo, working fine. You can update the condition inside if block as per requirement.

const licenseSchema = Yup.object().shape<ObjectSchemaDefinition<FormData>>({
  licenseStart: Yup.date().typeError('required'),
  licenseEnd: Yup.date().typeError('required')
    .test('checkEndDate', '', function (value) {
      const { path, parent, createError } = this;
      if ((parent.licenseStart).getTime() >= value.getTime()) {
        return createError({
          path,
          message: 'License end date cannot be before start date',
        });
      }
      return true;
    }),
}),
  • Related