最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Yup don't trigger the error if value typing starts with 0 - Stack Overflow

programmeradmin1浏览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?

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
Add a ment  | 

1 Answer 1

Reset to default 5

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.

发布评论

评论列表(0)

  1. 暂无评论