Basically, I have a field need validate like this:
export const validationSchemaWithdraw = Yup.object().shape({
amount: Yup.number()
.min(1, 'The minimum amount is one')
.typeError('The amount invalid')
.required('The amount is required'),
});
If I type the amount equal to 0, error should trigger. But if value is 01 nothing happen.
How to my field trigger the error if value typing starts with 0?
CodePudding user response:
Since you're decalring the value type as number
on yup schema, the input value will be casted to number before validation. A value like "01" will be parsed to 1, which is valid based on your validation chain.
A way to achieve the behaviour you're expecting is to add a custom test
function to your validation chain and testing the leading zero case. This requires accessing the field's original value as a string (before being casted to number by yup) otherwise leading zero will be dismissed by parsing. So be sure the type of your input field is "string".
const SignupSchema = Yup.object().shape({
amount: Yup.number()
.min(1, 'The minimum amount is one')
.typeError('The amount invalid')
.required('The amount is required')
.test(
'no-leading-zero',
'Leading zero is not allowed',
(value, context) => {
return context.originalValue && !context.originalValue.startsWith('0');
}
),
});
Another option could be to change the value type to string
on your schema and using matches
regex to check the string format.