Skip to content

Validating not required form fields with Yup?

I want to validate a not required form field with Yup

const validationSchema = Yup.object().shape({
    firstname: Yup.string().required("First name is required").matches(/[A-Za-z]/,"Should contain only alphabets").min(3,'Should contain atleast ${min} alphabets`).max(20,`Should not exceed ${max} alphabets'),
    lastname: Yup.string().nullable().notRequired()
})

lastname: Yup.string.nullable().notRequired(). I don’t how to proceed further because I have multiple condition to validate the field if the input was given.

My validation condition are:

  1. Should contain only alphabets.
  2. Should be atleast minimum 2 and maximum 20 alphabets.

Answer

You should use similar match pattern you already have for firstname. One possible way of doing is like this:

const obj = {
    firstname: 'my name',
    lastname: 'asd'
  };
  const yupObj = yup.object().shape({
    firstname: yup.string().required("First name is required").matches(/[A-Za-z]/,"Should contain only alphabets").min(3,'Should contain atleast 3 alphabets').max(20,`Should not exceed 20 alphabets`),
    lastname: yup.string().nullable().notRequired().matches(/[a-zA-Z]{2,20}/, 'should have alphabets between 2 and 20')
  })
  yupObj
  .validate(obj)
  .then(function(value) {
    console.log(value); 
  })
  .catch(function(err) {
    console.log(err);
  });