TeaCupApp
TeaCupApp

Reputation: 11452

Allowing more then one special chars in password

I have regular expression which tests following rules,

  1. Password must have at-least one char.
  2. Password must have at-least one numeric.
  3. Password must have at-least one alphanumeric char.(More then one should be allowed)

My attempt is this,

/^([a-zA-Z+]+[0-9+]+[!@#$%^&*])$/

This works fine as for most cases except if I add more then one alpha-numeric chars.

Tests

The last test should get Passed but it fails. I know where things are wrong but couldn't get hang of the regex magic. My thoughts about what is wrong is,

[0-9+] // This + sign shows that you can have more then 1 of that range of numerics

Where,

[!@#$%^&*] // Does not have the + sign

I tried,

[!@#$%^&*+] // Does not have the + sign
[!@#$%^&*]+ // Does not have the + sign

Both didn't work. What am I missing?

Upvotes: 0

Views: 153

Answers (3)

Sameera Kumarasingha
Sameera Kumarasingha

Reputation: 2988

Try the following. It will work if a characters should be first, numerics should be second and alpahanumerics should be next.

/^[a-zA-Z]+[1-9]+[!@#$%^&*]+$/

Upvotes: 0

Ian
Ian

Reputation: 50905

Depending on what you actually need, from your confusing description of your situation, here are two regexes that I hope help. This first one requires that the password start with at least 1 Alphabetic character, have at least 1 Numeric character second, then at least 1 Special character last.

/^([a-zA-Z]+[0-9]+[!@#$%^&*]+)$/

http://jsfiddle.net/ECwP8/

If you don't require the characters to come in a specific order, you can try this regex:

/(?=[^a-zA-Z]*[a-zA-Z])(?=[^0-9]*[0-9])(?=[^!@#$%^&*]*[!@#$%^&*])/

http://jsfiddle.net/bJTTk/1/

This one simply requires that there be at least 1 Alphabetic character, at least 1 Numeric character, and at least 1 Special character, occur in the password in any order.

Upvotes: 1

Blender
Blender

Reputation: 298246

Why do you need to mash it all into one regex?

function test_password(password) {
    if (password.length < 2) return false;            // Minimum length
    if (!/[0-9]/g.test(password)) return false;       // Needs a number
    if (!/[a-z]/gi.test(password)) return false;      // Needs a letter
    if (!/[^a-z0-9]/gi.test(password)) return false;  // Needs a special char

    return true;
}

Upvotes: 1

Related Questions