Emad Dehnavi
Emad Dehnavi

Reputation: 3441

Yup validation with regex using matches problem

So I have below validation using Yup :

const myValidtion = yup
.string()
.trim()
.matches(/[abcdefghijklmnopqrstuvwxyz]+/ , 'Is not in correct format')
.required();

With this validation, hello world passes as expected. However, what confuses me is why hello WORLD or hello ,&$#$ world also pass.

On the other hand, if we only enter invalid characters like *%$&#$($#, this does not pass and shows me the error. So, as I can see, it only gives me the error if ALL the entry is invalid.

What I'm looking for is how to use the Yup matches method to not pass if the user enters, for example, hello ,*&) world.

Can anyone help me with this?

Upvotes: 53

Views: 158579

Answers (2)

angelacpd
angelacpd

Reputation: 724

This worked for me:

const validationSchema = yup.object().shape({
  password: yup
    .string()
    .required("Please enter your password")
    .matches(
      /^.*(?=.{8,})((?=.*[!@#$%^&*()\-_=+{};:,<.>]){1})(?=.*\d)((?=.*[a-z]){1})((?=.*[A-Z]){1}).*$/,
      "Password must contain at least 8 characters, one uppercase, one number and one special case character"
    ),
  confirmPassword: yup
    .string()
    .required("Please confirm your password")
    .oneOf([yup.ref('password'), null], "Passwords don't match.")
});

Breaking down the regex:

(?=.{8,}): Set the minimum number of characters

((?=.[!@#$%^&()-=+{};:,<.>]){1}): Verify if there is at least 1 character of the list "!@#$%^&*()-=+{};:,<.>"

(?=.*\d): Verify if there is a digit

((?=.*[a-z]){1}): Verify if there is a lower case alphabetical character

((?=.*[A-Z]){1}): Verify if there is an upper case alphabetical character

You can test the regex code at https://regex101.com/r/rYT2yE/1.

Upvotes: 38

jo_va
jo_va

Reputation: 13964

Your regex should cover your whole string, by using ^ and $ to signify start and end of string:

/^[abcdefghijklmnopqrstuvwxyz]+$/

Otherwise, it will match part of your string, which is why it matches when you have a mix of good and bad characters, but fails when every character is bad.

You can shorten the regex by using a character range like this:

/^[a-z]+$/

You can use this online tool to build and test your regex.

Upvotes: 53

Related Questions