user632323
user632323

Reputation: 29

Regex Javascript

I am using the below regex in JavaScript for password policy check:

^.*(?=.{8,})(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[@#$_])(?=.*[\d\W]).*$

I tried the above regex using online regex checker http://www.nvcc.edu/home/drodgers/ceu/resources/test_regexp.asp

Test cases passed as expected, negative test cases failed. But same regex when deployed in application does not validate properly.

For eg: Tracker@123 does not work, where tRacker@123 works Asd56544#12 also works fine.

Can you please point out what's wrong in regex above?

Upvotes: 0

Views: 506

Answers (2)

Eugene
Eugene

Reputation: 11280

My advice is to separate this regex into several simple regex'es. You may assign rules for your password, and for every rule you can assign a regex.

For example

  1. Rule №1. Minimal length of password = 8 characters (can be done without regex)
  2. Rule №2. At least one digit is required. ( /[0-9]/ )
  3. Rule №3. At least one letter is required ( /[a-z]/i)
  4. Rule №4. Illegal characters for password ( regex for some characters you don't want users to use in passwords)
  5. Rule №n - some little regex

(and so on)

With this approach, it will be more easier to manage your validation in sooner time. For example after a year, you'll have to change your password policy. You'll forget what your big regex is meaning (and will spend a lot of time changing that big regex, or doing a new one). But with little separates regexes (meaning rules) you easily configure your password policy

Upvotes: 1

David
David

Reputation: 8670

Are you sure you syntax is correct?

Have a look at this JSfiddle, in it all the test cases pass

http://jsfiddle.net/pCLpX/

Upvotes: 0

Related Questions