0

I know this is a simple thing. but i just cant make it work.

Req: A word which contain at least one number, alphabets (can be both cases) and at least one symbol (special character).

In c# (?=.[0-9])(?=.[a-zA-z])(?=.*[!@#$%_]) worked. But in javascript its not working. Seems like it always look for number at the beginning since my condition starts with number in the regexp.f

Can anyone give me a regexp that can be used in javascript?

-Rakesh

2
  • 2
    Show us your Javascript code. Commented Jan 6, 2010 at 18:17
  • Super useful+free tool for debugging regular expressions: weitz.de/regex-coach Commented Jan 6, 2010 at 18:19

4 Answers 4

2

JavaScript does support lookaheads. However, your groups expect that there's at least on character before the number and letter (because they start with just a dot .). Try adding a * to those two dots:

var pattern = /(?=.*[0-9])(?=.*[a-zA-z])(?=.*[!@#$%_])/;
pattern.test('xxx'); // false
pattern.test('111'); // false
pattern.test('!!!'); // false
pattern.test('x1!'); // true

I'm seeing the same problem with this regular expression in C#, too.

Sign up to request clarification or add additional context in comments.

Comments

1

Just to cover the obvious answer, given the requirements as stated I would use separate tests.

/[0-9]/.test(string) && /[a-z]/i.test(string) && /[!@#$%_]/.test(string)

If you're interested in abstracting this away, one way is to store the tests in an array.

var tests = [ /[0-9]/, /[a-z]/i, /[!@#$%_]/ ];

And one way to evaluate multiple tests without modifying the scope of surrounding code, simply shoehorning this into a closure, follows.

var passes = (function(){
    for (var i=0; i<tests.length; i++)
        if (!tests[i].test(string)) return false;
    return true;
})();

Comments

0

I don't think javascript supports those lookaheads. Try

/(.*[a-zA-Z].*[0-9].*[!@#$%_].*|.*[a-zA-Z].*[!@#$%_].*[0-9].*|.*[0-9].*[a-zA-Z].*[!@#$%_].*|.*[!@#$%_].*[a-zA-Z].*[0-9].*|.*[0-9].*[!@#$%_].*[a-zA-Z].*|.*[!@#$%_].*[0-9].*[a-zA-Z].*)/

Not expecting any points for elegance...

Edit: As bdukes pointed out, js does support lookaheads. However, this (ugly) expression does work.

1 Comment

Haha, sorry. That's what happens when I answer questions before having coffee.
0

You can have a very long reg exp, with the three character classes repeated in differtent order, or use more than one test-

function teststring(s){
 return /^[\da-zA-Z!@#$%_]+$/.test(s) &&
 /\d/.test(s) && /[a-zA-Z]/.test(s) && /[!@#$%_]/.test(s);
}

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.