简体   繁体   中英

Symbols as optional character in regex

Currently here's how I do my regex:

var myPassword = $('#reg_password').val();
if (myPassword.match(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/)) {}

From the regex above, myPassword should contain at least 1 digit, 1 upper case and lower case. Now I want to add symbols as optional. I tried adding

([@$!%*#?&]?)

at various places in my regex above but it doesn't work...

Don't try to put everything in a single regex. Just test your requirements separately!

if (myPassword.length >= 8 &&
    /[a-z]/.test(myPassword) &&
    /[A-Z]/.test(myPassword) &&
    /\d/.test(myPassword) &&
    /[@$!%*#?&]/.test(myPassword)) {
}

您可以像这样简单地在[0-9a-zA-Z]添加符号:

/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z@$!%*#?&]{8,}$/

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