I'm using input type=number
and validation to it.
What I am trying to do:
only numbers allowed
value is required
yup.object().shape({ fieldName: yup.number().typeError("only numbers allowed").required("value required").min(0) })
But it returns always only typerror
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.
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
});