大家好,我有一个密码验证器,我在使用时遇到了问题,它很长,我认为如果可能的话可以缩短和简化。
谁能帮我简化一下。我在谈论 checkValidPassword() 函数。
function check(input) {
if (input.value != document.getElementById('password').value) {
input.setCustomValidity('Password Must be Matching.');
} else {
// input is valid -- reset the error message
input.setCustomValidity('');
// check the length of the password
checkValidPassword(input);
}
}
function checkValidPassword(input) {
var password = document.getElementById('password');
var confirm_password = document.getElementById('confirm password');
if (password.value.length < 8) {
password.setCustomValidity('Password must contain at least 8 characters!');
} else {
var re = /[0-9]/;
if (!re.test(password.value)) {
password.setCustomValidity('password must contain at least one number (0-9)!');
} else {
password.setCustomValidity("");
}
}
}
我正在尝试实现一种方法,让用户至少还必须包含一个数字。我在想
str.match(/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])([a-zA-Z0-9]{8,})$/)
我是否会在带有 $$ 的 if 语句中包含它以符号化 并检查字符?
if(password.value.length < 8 && str.match(/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])([a-zA-Z0-9]{8,})$/)) {
最佳答案
这本质上是一个代码审查问题,但是好吧...我会将您的函数重写为:
function checkPassword() {
var password = document.getElementById('password');
var confirm_password = document.getElementById('confirm password');
if (password.value != confirm_password.value) {
password.setCustomValidity('Password Must be Matching.');
return false;
}
if(password.value.length < 8 ) {
password.setCustomValidity('Password must contain at least 8 characters!');
return false;
}
if(!/[0-9]/.test(password.value)) {
password.setCustomValidity('password must contain at least one number (0-9)!');
return false;
}
return true;
}
基本上,单独检查每个条件并在失败时立即返回,从而避免额外的缩进(“提前退出”)。这有点冗长,但比怪物正则表达式更具可读性,尤其是当您不确定它的作用时。
关于javascript - 将这两个功能合二为一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27123359/