5

I need to validate a password with these rules:

  • 6 to 20 characters
  • Must contain at least one digit;
  • Must contain at least one letter (case insensitive);
  • Can contain the following characters: ! @ # $ % & *

The following expression matches all but the last requirement. What can I do with the last one?

((?=.*\d)(?=.*[A-z]).{6,20})

Guilherme
  • 7,839
  • 9
  • 56
  • 99
  • Not a regex expert, but couldn't you just add a `[!@#\$%&\*]?` too it? – Jordan Sep 04 '13 at 20:59
  • 1
    Which language Java, javascript....?? – Rahul Tripathi Sep 04 '13 at 20:59
  • Do you mean "can contain the following characters in addition to letters and numbers?" – Explosion Pills Sep 04 '13 at 21:04
  • I think there's an implicit "must not contain characters other than alphanumerics and the specific punctuation (from the fourth rule)." If not, this should be even easier. – Brian Cain Sep 04 '13 at 21:06
  • possible duplicate of [PHP regular expression for strong password validation](http://stackoverflow.com/questions/2637896/php-regular-expression-for-strong-password-validation) – dawg Sep 04 '13 at 21:08

3 Answers3

8

I'm not completely sure I have this right, but since your last requirement is "Can contain the following characters: !@#$%&*" I am assuming that other special characters are not allowed. In other words, the only allowed characters are letters, digits, and the special characters !@#$%&*.

If this is the correct interpretation, the following regex should work:

^((?=.*\d)(?=.*[a-zA-Z])[a-zA-Z0-9!@#$%&*]{6,20})$

Note that I changed your character class [A-z] to [a-zA-Z], because [A-z] will also include the following characters: [\]^_`

I also added beginning and end of string anchors to make sure you don't get a partial match.

Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
1

Regex could be:-

^(?=.*\d)(?=.*[a-zA-Z])[a-zA-Z0-9!@#$%&*]{6,20}$

How about this in Javascript:-

function checkPwd(str) {
    if (str.length < 6) {
        return("too_short");
    } else if (str.length > 20) {
        return("too_long");
    } else if (str.search(/\d/) == -1) {
        return("no_num");
    } else if (str.search(/[a-zA-Z]/) == -1) {
        return("no_letter");
    } else if (str.search(/[^a-zA-Z0-9\!\@\#\$\%\^\&\*\(\)\_\+]/) != -1) {
        return("bad_char");
    }
    return("ok");
}

Also check out this

Community
  • 1
  • 1
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
1
^(?=.*\d)(?=.*[a-zA-Z])[a-zA-Z0-9!@#$%&*]{6,20}$
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405