Home > Net >  How do I validate 2 conditions for a single field using Yup validation
How do I validate 2 conditions for a single field using Yup validation

Time:10-28

I want to check if the text field in the title has been filled or not and I also want to set the limit of the text box to 300 characters. If I try either of these conditions independently they work. However if I try them both at the same time then the character limit validation gets executed but not the other one.

const validationSchema = Yup.object().shape({

     title: Yup.string().required().label("Title"),

     title: Yup.string().test('len', 'Title must be less than 300 characters', val => 
            val.toString().length < 300)
   })

CodePudding user response:

You're passing an object to the .shape function and having the title key in there twice results in the first definition being overwritten.

What you would actually need to do, is to create one entry for title and then have all validation logic as the value:

const validationSchema = Yup.object().shape({

     title: Yup.string()
              .test('len', 'Title must be less than 300 characters', val => 
            val.toString().length < 300)
              .required()
              .label("Title")
})

You could also change the test for the length to the built-in .max operation:

const validationSchema = Yup.object().shape({

     title: Yup.string()
              .max(300, 'Title must be less than 300 characters')
              .required()
              .label("Title")
})
  • Related