简体   繁体   中英

Javascript regular expression for “at least X characters, have a capital letter and a number”

I have a regular expression for a password field which I know works perfectly ie Must be at least 6 characters in length, have a capital letter, a number and can contain special characters. When I try to apply this regex within Javascript it doesn't seem to validate. My Javascript function is below.

function (word) {
    var weakRegEx = new RegExp('(?=^.{6,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$');
    var result = weakRegEx.test(word);
    return result;

Since you're writing a string literal, you need to escape the \\ characters.

You should use a regex literal instead:

var weakRegEx = /(?=^.{6,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$/;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM