我想用正则表达式确认密码,所以我决定分别验证密码和确认密码。但是密码和确认密码不匹配。因此,如何通过正则表达式javascript重新匹配密码并确认密码? 谢谢。
// Validate password
if(upassid == "") {
printError("passErr", "Please enter your Password*");
} else {
var regex = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s).{8,15}$/;
if(regex.test(upassid) === false) {
printError("passErr", "Please enter a valid Password!*");
} else{
printError("passErr", "");
passErr = false;
}
}
// Validate confirm password
if(unpassid == "") {
printError("unpassErr", "Please enter your Password*");
} else {
var regex = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s).{8,15}$/;
if(regex.test(unpassid) === false) {
printError("unpassErr", "Please enter a valid Password!*");
} else{
printError("unpassErr", "");
unpassErr = false;
}
}
答案 0 :(得分:1)
从您的代码看来,您在变量中同时具有密码和确认的密码。因此,如果它们匹配,我认为您不需要正则表达式进行比较。您可以这样做:
if (upassid != unpassid) {
printError("unpassErr", "Passwords don't match");
}
因此,您的代码可能如下所示:
var regex = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s).{8,15}$/;
if (upassid == "") {
printError("passErr", "Please enter your Password*");
} else if (unpassid == "") {
printError("unpassErr", "Please confirm your Password!*");
} else if (upassid != unpassid) {
printError("unpassErr", "Passwords do not match!*");
} else if(regex.test(upassid) === false) {
printError("passErr", "Please enter a valid Password!*");
} else{
printError("passErr", "");
printError("unpassErr", "");
passErr = false;
unpassErr = false;
}
我已经对其进行了简化,因为您无需检查密码和确认是否都与您的正则表达式匹配,因此只需要密码进行匹配即可,并且确认与密码相同。
答案 1 :(得分:0)
为什么在验证密码(upassid)后检查reqex以确认密码(unpassid)?为什么不只比较unpassid ==upassid
?
if(upassid == "") {
printError("passErr", "Please enter your Password*");
} else {
var regex = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s).{8,15}$/;
if(regex.test(upassid) === false) {
printError("passErr", "Please enter a valid Password!*");
} else if(unpassid !=upassid){
printError("passErr", "Confirm Password does not match!*");
} else {
printError("unpassErr", "");
unpassErr = false;
}
}