Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

369
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!