简体   繁体   English

是的,在匹配中使用 not(!) 时验证不起作用 function

[英]Yup validation doesn't work when use not(!) in matches function

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.我有一个带有 React 和 next.js 的项目。我使用 formik 处理我的 forms 和 Yup 进行验证我有一个输入,我想对其执行一些验证。

  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此字段不应包含任何数字,否则我会显示此消息 => 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(/^[-ۿ\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但在这种情况下,条件 2 总是被认为是错误的。我认为 (!/\d/) 是错误的,但我不知道如何使用匹配 function 否定

According to yup you can use .matches using this shape: string.matches(regex: Regex, message?: string | function): Schema .根据yup你可以使用.matches使用这个形状: 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+$/ .如果你想验证字符串不包含数字,而不是使用(!/\d/)你应该使用/\D+$/

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

See working example查看工作示例

You can do it with the test() function from Yup like the following:您可以使用 Yup 的test() function 来完成它,如下所示:

.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.我相信 Yup 应该为.match()提供一个相反的 function 因为你并不总是想要匹配,有时你想根据正则表达式测试你的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM