Search code examples
typescriptyup

Yup schema - Numbers less than 10 to have a trailing 0


In Yup I have this schema:

const ticketVSchema = yup.object({
        team: yup
            .number()
            .required('The number is required')
    });

I need a condition to ensure if the user enters 0-9, it errors asking for a trailing 0, anything else is fine.

Any ideas?

Thanks.


Solution

  • You can write a custom .test() function that handles this logic.

    const ticketVSchema = yup.object({
      team: yup
        .number()
        .test("is not 0-9", "asking for a trailing 0", value => {
          if (value && value > -1 && value < 10) {
            return false;
          }
    
          return true;
        })
        .required("The number is required")
    });
    
    ticketVSchema.isValidSync({team: 5}); // false
    ticketVSchema.isValidSync({team: 10}); // true