0

Currently I'm attempting to create a regular expression to validate an user input field which requires the input to contain at least one of each of the following:

  • an upper-case character
  • a digit
  • one of the following special characters: & @ ! # +

I attempted to create a regular expression that will validate the input correctly:

/^([a-zA-Z+]+[0-9+]+[&@!#+]+)$/i.test(userpass);

However, the input is not validated correctly. How should I go about doing that?

3
  • 1
    Your regexp requires that all the letters come first, then all the numbers, then all the special characters. Also, you allow + in each of those groups, why? Commented Jul 2, 2013 at 6:16
  • @Qantas94Heavy - the list of special characters is in the OP's regex. Reading between the lines I think they want the test string to contain at least one of those "special" characters, at least one letter, and at least one digit, in any order - but that regex enforces a specific order as per Barmar's comment. Commented Jul 2, 2013 at 6:30
  • possible duplicate of Password validation regex Commented Jul 2, 2013 at 7:01

2 Answers 2

1

Try this:

/[a-z]/i.test(userpass) && /[0-9]/.test(userpass) && /[&@!#+]/.test(userpass)
Sign up to request clarification or add additional context in comments.

Comments

1

you can simplify the regex with lookahead

 ^(?=.*[&@!#+])(?=.*[A-Z])(?=.*\d).+$
  ------------- --------- -------
      |        |         |->match only if there's a digit ahead
      |        |->match only if there's a uppercase alphabet ahead
      |->match only if there's any 1 of [&@!#+]

[A-Z] would match a single uppercase letter

\d would match a single digit


OR use search

if(input.search(/\d/)!=-1 && input.search(/[&@!#+]/)!=-1) && input.search(/[A-Z]/)!=-1)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.