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

javascript - Yup validation doesn't work when use not(!) in matches function - Stack Overflow

programmeradmin2浏览0评论

I have a project with React and next js. I use formik for handling my forms and Yup for validations I have an input and I want perform some validations on it.

  1. this field must be required so if user don't enter any information I show this message => Required
  2. this field should not contain any numbers otherwise I Show this message => Wrongggg
  3. this field must only contain Persian characters otherwise I Show this message => only Persian chars

this is my schema

 Yup.string()
            .required("Requiredddd")
            .matches(!/\d/, 'Wrongggg'),
            .matches(/^[\u0600-\u06FF\s]+$/, 'Only persian chars')

I have a project with React and next js. I use formik for handling my forms and Yup for validations I have an input and I want perform some validations on it.

  1. this field must be required so if user don't enter any information I show this message => Required
  2. this field should not contain any numbers otherwise I Show this message => Wrongggg
  3. this field must only contain Persian characters otherwise I Show this message => only Persian chars

this is my schema

 Yup.string()
            .required("Requiredddd")
            .matches(!/\d/, 'Wrongggg'),
            .matches(/^[\u0600-\u06FF\s]+$/, 'Only persian chars')

But in this case condition number 2 always Considered wrong.i think (!/\d/) is wrong but I haven't any idea how can use matches function Negatively

Share Improve this question edited Jan 7, 2023 at 9:03 Ali Ehyaie asked Apr 6, 2022 at 13:13 Ali EhyaieAli Ehyaie 1,2604 gold badges14 silver badges33 bronze badges 1
  • Did you try .matches(/\D/, 'Wrongggg') instead? – lissettdm Commented Apr 6, 2022 at 13:15
Add a comment  | 

2 Answers 2

Reset to default 10

You can do it with the test() function from Yup like the following:

.test('name Your Test here', 'your validation message', (value) => !yourRegex.test(value))

I believe Yup should provide an opposite function for .match() since you don't always want to match, sometimes you want to test your value against the regex.

According to yup you can use .matches using this shape: string.matches(regex: Regex, message?: string | function): Schema. If you want to validate that the string doesn't contain numbers, instead of using (!/\d/) you should use /\D+$/.

 Yup.string()
            .required("Requiredddd")
            .matches(/\D+$/, 'Wrongggg')
            .matches(/^[\u0600-\u06FF\s]+$/, 'Only persian chars')

See working example

发布评论

评论列表(0)

  1. 暂无评论