Clone required message in typeError using Error Customization

Viewed 8

In yup we have Error Customization, which allows us to create default error messages when we don't pass any error message to the schema.

Is it possible to define in the Error Customization a typeError message that will always clone the required message from the schema?

I.e.: I have this defined schema:

export const employeeValidation = yup.object().shape({
  employeeFirstName: yup
    .string()
    .matches(REGEX_PATTERNS.name.pattern, REGEX_PATTERNS.name.err)
    .required('The employee name is required'),
  employeeLastName: yup
    .string()
    .matches(REGEX_PATTERNS.name.pattern, REGEX_PATTERNS.name.err)
    .required('The employee last name is required'),
  employeeEmail: yup
    .string()
    .email('Please enter the employee personal email address in format: theirname@example.com'),
  employeeNationality: yup.string().required('The employee nationality is required'),
  employmentCountry: yup.string().required('The employment country is required'),
  employmentState: yup.string().when('employmentCountry', (employmentCountry: any) => {
    if (EOR_SUPPORTED_PROVINCE_COUNTRIES.has(employmentCountry)) {
      return yup.string().required('You must select an option');
    }
    return yup.string();
  }),
  workVisa: yup.boolean().typeError('You must choose an option').required('You must choose an option'),
});

However sometimes the employeeNationality is null, which must trigger a validation error, but it triggers the typeError, which displays the default ugly error message. I want the typeError message to always be the same as the required error message, unless specified another message. Note that the workVisa has both messages defined, but it's an overkill to always specify they both equal.

0 Answers
Related