jQuery Validate 插件为表单提供了强大的验证功能,让客户端表单验证变得更简单,同时提供了大量的定制选项,满足应用程序各种需求。该插件捆绑了一套有用的验证方法,包括 URL 和电子邮件验证,同时提供了一个用来编写用户自定义方法的 API。
基本用法如下:
一、导入 js 库
<script src="http://XXXXX/jquery-validation-1.14.0/lib/jquery.js"></script>
<script src="http://XXXXX/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script>
二、使用
html:
<form novalidate="novalidate" id="deliver-form" action="XXXX" accept-charset="UTF-8" method="post">
<label >收货人:</label>
<input type="text" name="deliver_user">
</form>
script:
$('#deliver-form').validate({
rules:{
deliver_user:{ required:true},
},
messages:{
deliver_user:{ required:'收货人姓名不能为空'},
},
submitHandler:function(form){
$(form).ajaxSubmit({
success:function(res){
//提示操作成功或失败
}
})
}
});
上面的用法对于页面第一次加载form就生成的话,那么是能够正常验证的,但如果form是动态生成的,例如使用vue变量判断。
html:
<form v-if="isShow" novalidate="novalidate" id="deliver-form" action="XXXX" accept-charset="UTF-8" method="post">
<label >收货人:</label>
<input type="text" name="deliver_user">
</form>
因为没等Dom渲染完成就调用,是获取不到form。一定要等到渲染完成才能获取form,所以可以使用 setTimeout(function(){ //获取dom的代码 },500);。