0
var pattern = /^[a-zA-Z0-9!@#$%^&*()~]+$/;

var username = document.getelementbyId("txtUsername").value;

if(pattern.test(username) == false) {

    alert("Invalid Username");
}

The above regex pattern is not working. I want a Regular expression where the password must contain at least one lowercase letter, one Uppercase letter, one digit and one special character.

Sasidhar Vanga
  • 3,384
  • 2
  • 26
  • 47
Pearl
  • 8,373
  • 8
  • 40
  • 59
  • 1
    `username`, password? Which is it? – deceze Aug 16 '13 at 09:19
  • Use 4 separate tests. Offload it into a separate function for readability, is my advice. – Joe Simmons Aug 16 '13 at 09:22
  • 1
    [Don't force people to use a specific format of password](http://xkcd.com/936/) – Niet the Dark Absol Aug 16 '13 at 09:30
  • @Kolink Yes and no. Enforcing a *minimum entropy* is not a bad idea. OP here is trying to do so by enforcing entropy in the alphabet used. Mr. XKCD is suggesting entropy in the dimension of length instead. Either dimension should be enforced. Ideally you calculate how much entropy a password has based on alphabet * length and enforce it that way. This is all somewhat meaningless though. Even "aaaaaaaa" is a great password if an attacker has to *expect* the alphabet to *possibly be* a-zA-Z0-9!@#$%^&*()~. – deceze Aug 16 '13 at 09:35

2 Answers2

1

Then you will have to make separate tests:

if (/[a-z]/.test(username) && /[A-Z]/.test(username) && ...)

You cannot reasonably express your requirements in a single regex.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • Yes, I've also tried that but it's some kinda long. Is there any short version in single Regular expression...? – Pearl Aug 16 '13 at 09:20
  • "You cannot reasonably express your requirements in a single regex." It's possible, but it will be a long and confusing regex. – Joe Simmons Aug 16 '13 at 09:20
  • @Joe I.e. "not reasonable"... :) – deceze Aug 16 '13 at 09:22
  • @User No. You would have to express each possible permutation in your regex. If you specify a group of characters, you don't know which one matched. So you'd have to enforce individual groups: `[a-z][A-Z]\d`, meaning "one lower case, one upper case, one digit". But that also fixes the order of their occurrence, so you'd also have to test for `[a-z][A-Z]\d|\d[a-z][A-Z]` and every other possible permutation. Regexen simply aren't the right tool to express this in one go. – deceze Aug 16 '13 at 09:24
1
if (!/[a-z]/.test(username) 
    || !/[A-Z]/.test(username) 
    || !/[0-9]/.test(username) 
    || !/[!@#$%^&*()~]/.test(username)) {
  alert("Invalid");
}

You have to have the checks separated.

Carl Mastrangelo
  • 5,970
  • 1
  • 28
  • 37