Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

534
Vistas
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.
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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);
  });
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda