Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - Password REGEX with min 6 chars, at least one letter and one number and may contain special characters

I need a regular expression with condition:

  • min 6 characters, max 50 characters
  • must contain 1 letter
  • must contain 1 number
  • may contain special characters like !@#$%^&*()_+

Currently I have pattern: (?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-9]{6,50})$

However it doesn't allow special characters, does anybody have a good regex for that?

Thanks

Question&Answers:os

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

1 Reply

0 votes
by (71.8m points)

Perhaps a single regex could be used, but that makes it hard to give the user feedback for which rule they aren't following. A more traditional approach like this gives you feedback that you can use in the UI to tell the user what pwd rule is not being met:

function checkPwd(str) {
    if (str.length < 6) {
        return("too_short");
    } else if (str.length > 50) {
        return("too_long");
    } else if (str.search(/d/) == -1) {
        return("no_num");
    } else if (str.search(/[a-zA-Z]/) == -1) {
        return("no_letter");
    } else if (str.search(/[^a-zA-Z0-9!@#$\%^&*()\_+]/) != -1) {
        return("bad_char");
    }
    return("ok");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...