skip to Main Content

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

2

Answers


  1. 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
    });
    
    Login or Signup to reply.
  2. function validateNumber(input) {
      if (input === "") {
        return "Error: Input cannot be empty.";
      }
    
      if (!/^d+$/.test(input)) {
        return "Error: Input must contain only numeric characters.";
      }
    
      return "Success: Input is a valid number.";
    }
    
    // Example usage:
    const userInput = prompt("Enter a number:");
    const validationResult = validateNumber(userInput);
    
    console.log(validationResult);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search