开发者

Again some regex problems (password strength) in JavaScript

I'm again struggling with some regex syntax for a password validation.

The rules for a password are:

  1. must contain at least number
  2. must contain at least one special character of the set . : , ; - $ % _ = ! ?
  3. must NOT contain other special characters than the set above in rule 2
  4. may contain one or more regular word characters lowercase or uppercase
开发者_运维知识库

I've come so far:

var regex = /.*(?=.*[\.:,;\-\$%=\!\?])(?=.*\d).*/;

But this does only meet the rules 1 and 2 and allows any other special characters.

Can anyone help?


must contain at least number

/\d/

must contain at least one special character of the set . : , ; - $ % _ = ! ?

/[.:,;\-$%_=!?]/

must NOT contain other special characters than the set above in rule 2 may contain one or more regular word characters lowercase or uppercase

/^[a-z0-9.:,;\-$%_=!?]+$/

Putting it all together

/^(?=\D*\d)(?=[a-z0-9]*[^a-z0-9])[a-z0-9.:,;\-$%_=!?]+$/i

And if you want to enforce a minimal length you can use {6,} or something similar,

/^(?=\D*\d)(?=[a-z0-9]*[^a-z0-9])[a-z0-9.:,;\-$%_=!?]{6,}$/i


Your code would be much more readable and understandable if you did not use regular expressions for this problem. Create one function for each rule (some of which can use regular expressions if you wish), then your check looks like:

if contains_digits(password) && \
   contains_special(password) && \
   only_contains_specific_chars(password) && \
   ...

Then it becomes trivial to add new rules or adjust existing rules. If you take a regular expression you don't understand, when the day comes when you have to modify it you will spend an entire day trying to figure it out.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜