如何在用户点击其他地方时验证表单

时间:2014-01-31 07:00:47

标签: html5 validation

对于我正在制作的注册表单,我想验证密码,以便用户必须输入包含至少一个大写字母和至少一个数字的密码。

我在这里实现了这个: http://jsfiddle.net/k9aHV/1/

<form action="login.php" method="post">
                    <p><b>UserName:</b> <input type="text" required pattern="\w+" name="fname"/></p>
                    <p><b>Password:</b> <input type="password" required pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z])\w{6,}" name="password" onblur="this.setCustomValidity(this.validity.patternMismatch ? 'Password must contain at least 6 characters, including UPPER/lowercase and numbers' : '');if(this.checkValidity()) form.password1.pattern = this.value;"></p>
                    <p><b>Confirm Password:</b> <input type="password" required pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z])\w{6,}" name="password1" onblur="
                    this.setCustomValidity(this.validity.patternMismatch ? 'Please enter the same password as above' : '');"/></p>
                    <p><b>Email:</b> <input type="email" name="email"/></p>
                    <input type="submit"/>
                </form>

目前,仅当用户按下提交时才会验证该字段。

如何调整代码,以便用户在输入字段中点击或点击后立即验证代码?

1 个答案:

答案 0 :(得分:2)

您可以触发模糊的原生验证

input.addEventListener('blur', function(e) {
    e.target.checkValidity();
});

问题是您无法以编程方式触发验证错误弹出窗口。 一种解决方法是以编程方式单击提交按钮,但弹出窗口仅显示第一个无效的输入元素!

更加用户友好的解决方案是在元素中显示验证消息。

请参阅此JSFiddle

var idx;    
var passwordInputs = document.querySelectorAll('input[type="password"]');
for(idx=0; idx< passwordInputs.length; idx++) {
    //set custom validation
    passwordInputs[idx].addEventListener('input', function(e) {
        if(e.target.validity.patternMismatch) {
            e.target.setCustomValidity('Password must contain at least 6 characters, including UPPER/lowercase and numbers');
        }
        else {
            e.target.setCustomValidity('');
        }
    });
}

//code starting here is to show the validation message in a span element
function showValMessage(elem, msg) {
    var span = elem.parentNode.querySelector('span');
    span.innerText  = msg;
}

var inputs = document.querySelectorAll('input');
for(idx=0; idx< inputs.length; idx++) {
    var input = inputs[idx];

    //validate on blur
    input.addEventListener('blur', function(e) {
        e.target.checkValidity();
    });

    //show validation message
    input.addEventListener('invalid', function(e) {
        showValMessage(e.target, e.target.validationMessage);
    });

    //hide validation message. There is on valid event :(
    input.addEventListener('input', function(e) {
        if(e.target.validity.valid) {
            showValMessage(e.target, '');
        }
    });
}