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?
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?
Share Improve this question asked Sep 27, 2021 at 9:24 Huy Hoang NguyenHuy Hoang Nguyen 591 silver badge5 bronze badges 2- On your yup schema you're defining value type as number, so '01' gets parsed to 1 and that's indeed a valid value. – lbsn Commented Sep 27, 2021 at 10:17
- Thanks, @lbsn. How can I get what I expected? – Huy Hoang Nguyen Commented Sep 27, 2021 at 10:19
1 Answer
Reset to default 5Since 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.