javascript - 将这两个功能合二为一

标签 javascript validation passwords

大家好,我有一个密码验证器,我在使用时遇到了问题,它很长,我认为如果可能的话可以缩短和简化。

谁能帮我简化一下。我在谈论 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/

相关文章:

javascript - 为什么忽略 Angular $http 服务回调?

javascript - 如果有人触摸输入框并将其留空,我如何使用 React Native 验证输入文本(已修改)

c# - 寻找样本来验证 UTF-8

android - Android中的密码提示字体

amazon-web-services - 允许用户在阻止访问 IAM 的同时更改自己的密码的 AWS IAM 策略

javascript - 嵌套菜单停止触发未直接点击<li>s

javascript - 如何在不同的函数中使用变量?

javascript - 在vue组件中添加html

jquery - 如何抑制无效电子邮件地址的 jQuery 警告?

ruby-on-rails - 需要旧密码才能创建新密码