javascript jquery关于模糊验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4263984/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 10:49:33  来源:igfitidea点击:

jquery on blur validation

javascriptjqueryvalidation

提问by Ra.

I am using jquery validation plugin. Here after click the "submit" button, my form gets validated. But i need onblur validation, for ex: if the html textbox/other elemets lost their focus(onblur) then i need to validate the corresponding field. so How do I modify the below code?

我正在使用 jquery 验证插件。单击“提交”按钮后,我的表单将得到验证。但我需要 onblur 验证,例如:如果 html 文本框/其他元素失去焦点(onblur),那么我需要验证相应的字段。那么如何修改下面的代码呢?

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript" src="jquery.validate.js"></script>
<script type="text/javascript" >
$(document).ready(function() {
$.validator.addMethod("email", function(value, element)
{
return this.optional(element) || /^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$/i.test(value);
}, "Please enter a valid email address.");

$.validator.addMethod("username",function(value,element)
{
return this.optional(element) || /^[a-zA-Z0-9._-]{3,16}$/i.test(value);
},"Username are 3-15 characters");

$.validator.addMethod("password",function(value,element)
{
return this.optional(element) || /^[A-Za-z0-9!@#$%^&*()_]{6,16}$/i.test(value);
},"Passwords are 6-16 characters");

// Validate signup form
$("#signup").validate({
rules: {
email: "required email",
username: "required username",
password: "required password",
},
});
});
</script>

Thanks in advance

提前致谢

回答by Surreal Dreams

According to the docs, you enable validation when inputs lose focus with onfocusout:

根据文档,您可以在输入失去焦点时启用验证onfocusout

$(".selector").validate({
    onfocusout: false
})

In your case, specifically:

在您的情况下,特别是:

$("#signup").validate({
    onfocusout: false,    //this setting is what you need
    rules: {
        email: "required email",
        username: "required username",
        password: "required password"
    }
});