Differences in regular expression behavior
P粉996763314
P粉996763314 2024-04-01 13:33:29
0
1
355

I'm trying to build a regular expression to match fields that should contain 9 digits

I use the following regular expression

/^\d{9,9}$/

Now, the problem is when doing it

/^\d{9,9}$/.test("123456789") //returns true

However, when I try to use the same regular expression (passed in myRegex below) using Yup's match

'myField': yup
            .string()
            .nullable()
            .required('Field is required')
            .max(9, `Max length 9`)
            .matches(myRegex, {
                message: 'Field is invalid',
            }),

For the same input I get invalid message i.e. 123456789

Just wondering why this happens?

renew: Yes, use value.search(regex) , so in my case it runs "123456789".search(/^\d{9,9}$/)

Not sure if the above is the problem?

P粉996763314
P粉996763314

reply all(1)
P粉362071992

It seems your solution uses the wrong regular expression

Problems arise when Yup's search() method is used with regular expressions. The search() method returns the index of the first match and does not count the complete string.

Since "123456789" contains 9 consecutive digits, it satisfies the regular expression and the search() method returns the index of the first occurrence, which is 0. Since 0 is a true value, Yup interprets it as a failed match and returns an invalid message.

This is a regular expression you can try using /^\d{9}$/

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template