Bipin Bangwal
Bipin Bangwal

Reputation: 45

Validation In java script

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:

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?

Upvotes: 0

Views: 93

Answers (2)

Anirudha
Anirudha

Reputation: 32787

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)

Upvotes: 1

Barmar
Barmar

Reputation: 780663

Try this:

/[a-z]/i.test(userpass) && /[0-9]/.test(userpass) && /[&@!#+]/.test(userpass)

Upvotes: 1

Related Questions