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

377
Vistas
Validating a non-required number field with Yup

I'm trying to validate a number field that is optional, and therefore allowed to be empty. If there is a value in the field, it must be a positive number.

const schema = yup.object().shape({
    gpa: yup.number()
        .when('gpa', {
        is: (value) => value?.length > 0,
        then: yup.number().positive(numberPositiveMessage).typeError(numberMessage),
        otherwise: yup.number().notRequired().nullable(true).transform(value => (isNaN(value) ? undefined : value))
    },
    [
        ['gpa', 'gpa'],
    ]
);

It allows the rest of the form to validate when the field is empty, and when there is a positive number in there, but if I enter a negative number or a string it does not return any errors like it should.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Avoid using required() so that the field would be optional. It would only be validated if present.

gpa: yup
  .number()
  .positive()
  .nullable(true)
  .transform((_, val) => val === val ? val : null) // transform NaN to null
    

about 4 years ago · Juan Pablo Isaza Denunciar

0

For the next person that winds up here trying to do the same thing, this works for positive numbers that can be 0, null, undefined or an empty string but not any other string or a negative number:

const schema = yup.object().shape({
    gpa: yup.number()
         .typeError("GPA must be a number")
         .nullable()
         .moreThan(0, "Floor area cannot be negative")
         .transform((_, val) => (val !== "" ? Number(val) : null)),
    }
);

The Number cast triggers a type error on a string that will give you the error defined in .typeError() and using .moreThan() instead of .positive() allows you to have zero (switch to .positive() if you don't want to allow 0).

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