Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating a number field with yup, using custom message and checking for empty field

Tags:

javascript

yup

I am validating a field that can only take a positive decimal number. My Yup schema looks as follow:

yup.object().shape({
Duration: yup
    .number()
    .typeError('Please enter a duration. The field cannot be left blank.')
    .positive('Must be a positive number.'),
})

As a result,

  1. When the user enters a negative number (including 0), the 'Must be a positive number' message is displayed
  2. When the user leaves the field blank, the 'Please enter a duration. The field cannot be left blank' message is displayed.
  3. But, when the user enters a string such as (two minutes or any other string), the 'Please enter a duration. The field cannot be left blank' message is displayed which does not make sense.

I could change the typeError() message for something more generic but I was wondering if there was a more comprehensive way to handle the scenario.

So, when the user enters

  1. a string I can display a 'Must be a number type' message and,
  2. when the field is left blank, I can display the 'Please enter a duration. The field cannot be left blank' message.
like image 876
aadlc Avatar asked Jan 30 '26 08:01

aadlc


1 Answers

Here's my take on a more comprehensive way to handle the given scenario. We will use the required and minimum schemas.

yup.object().shape({
    Duration: yup
        .number("Must be a number type") // Validates for numerical value
        .positive("Must be a positive value") // Validates against negative values
        .required("Please enter a duration. The field cannot be left blank.") // Sets it as a compulsory field
        .min(1, "Hey! Your duration must be greater than or equal to 1!"), // Sets a minimum value});
});

These newly added schemas help to:

  • Mark the schema as required, which will not allow undefined or null as a value. required negates the effects of calling optional() and nullable()
  • Set the minimum value allowed. The ${min} interpolation can be used in the message argument.
like image 114
Chai Pin Zheng Avatar answered Jan 31 '26 21:01

Chai Pin Zheng



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!