Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

378
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda