Search code examples
javascriptformsvalidationyup

Add two errors to number validation


I'm using input type=numberand validation to it.
What I am trying to do:

  • if value is not number - show error only numbers allowed
  • if input is empty - show error value is required

yup.object().shape({ fieldName: yup.number().typeError("only numbers allowed").required("value required").min(0) })
But it returns always only typerror


Solution

  • You are trying to validate an input field or type = number, if an empty string is passed it bound to produce an error. The Yup validation is actively checking if the value is a valid JavaScript number, and empty values or non-numeric strings do not meet this criterion.

    1. Use yup.mixed() to allow both numbers and empty values
    2. Use the test method to define a custom validation rule

    Here's the modified code:

    
    import * as yup from 'yup';
    
    const schema = yup.object().shape({
      fieldName: yup
        .mixed() // Use mixed() to allow both numbers and empty values
        .test('is-number-or-empty', 'Only numbers allowed or value is required', (value) => {
          // Check if the value is a number or empty
          if (!value || !isNaN(value)) {
            return true; // Validation passed
          } else {
            return false; // Validation failed
          }
        })
        .typeError('Only numbers allowed'), // Type error message
    });