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

javascript - .notRequired on yup string not working if string is empty and still throws an error - Stack Overflow

programmeradmin1浏览0评论

I am trying to validate a string that if empty should not be validated but if there is a character then validation should start. I tried this but to no avail

iban: yup
      .string()
      .notRequired()
      .min(5, 'Minimum of 5')
      .max(34, 'Maximum of 34'),

If empty string as in '' it still throws a minimum of 5 error How can I fix this?

I am trying to validate a string that if empty should not be validated but if there is a character then validation should start. I tried this but to no avail

iban: yup
      .string()
      .notRequired()
      .min(5, 'Minimum of 5')
      .max(34, 'Maximum of 34'),

If empty string as in '' it still throws a minimum of 5 error How can I fix this?

Share Improve this question asked May 11, 2020 at 18:23 SImon HaddadSImon Haddad 8423 gold badges12 silver badges25 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

According to the docs on github, it says passing in undefined is acceptable, however the empty string does not equal undefined.

mixed.notRequired(): Schema
  Mark the schema as not required. Passing undefined as value will not fail validation.

I have a ticket out with the makers of yup to see if there is a way to do this with the built-in functionality. As a workaround, you can use a regular expression to acplish this with the match function.

iban: yup.string().matches(/^(|.{5,34})$/, "Between 5-34 characters")

Here's the sandbox: https://codesandbox.io/s/old-sound-rs6il

发布评论

评论列表(0)

  1. 暂无评论