1
votes

I'm struggling to create a successful regex using Yup. I want to validate a string that it only accepts letters, numbers and spaces. Any other character would invalidate the entire string. This is my code:

const nameRegex = /^[^a-zA-Z0-9 ]+$/g;

export const Schema = Yup.object().shape({
    name: Yup.string()
        .required('Name is Required')
        .matches(nameRegex, 'Name is not valid')
});

No matter what String I use, I get "Name is not valid" error from Yup.

"Tester 1" should pass and "Tester!% 2" should fail

How do I fix this?

1

1 Answers

0
votes

The expression you have is the opposite of what you need. That's because your character class starts with the negation operator: [^x] means anything but x.

Removing the negation from your character class should work.

/^[a-zA-Z0-9 ]+$/

Bear in mind that your expression requires a specific subset of Latin letters (a-z), and will fail to match François for example.