Yup validation not work when use not(!) in matches function

All we need is an easy explanation of the problem, so here it is.

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
            .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

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

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+$/.

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

See working example

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

Leave a Reply