Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
629 views
in Technique[技术] by (71.8m points)

javascript - Regex for checking that at least 3 of 4 different character groups exist

I'm trying to write a password validator.

How can I see if my supplied string contains at least 3 different character groups?

It's easy enough to check if they are existant or not ---but at least 3?

  • at least eight (8) characters

  • At least three different character groups

    upper-case letter

    lower-case letter

    numeric

    special characters !@#$%&/=?_.,:;-

(I'm using javascript for regex)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Just to learn - would this kind of requirement be possible to implement in pure regex?

That'd make it a rather hard to read (and therefor maintain!) solution, but here it is:

(?mx)
^
(
  (?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])                # must contain a-z, A-Z and 0-9
  |                                                # OR
  (?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%&/=?_.,:;\-]) # must contain a-z, A-Z and special
  |                                                # OR
  (?=.*[a-z])(?=.*[0-9])(?=.*[!@#$%&/=?_.,:;\-]) # must contain a-z, 0-9 and special
  |                                                # OR
  (?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%&/=?_.,:;\-]) # must contain A-Z, 0-9 and special
)
.{8,}                                              # at least 8 chars
$

A (horrible) Javascript demo:

var pw = "aa$aa1aa";
if(pw.match(/^((?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])|(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%&/=?_.,:;\-])|(?=.*[a-z])(?=.*[0-9])(?=.*[!@#$%&/=?_.,:;\-])|(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%&/=?_.,:;\-])).{8,}$/)) {
  print('Okay!');
} else {
  print('Fail...');
}

prints: Okay!, as you can see on Ideone.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...