微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

jQuery验证插件validation使用指南

在网站开发过程中,有时我们需要验证用户输入的信息是否符合我们的要求,所以我们会对用户提交的数据进行验证。验证分两次进行,一次是在客户端,一次是在服务端。客户端的验证可以提升用户的体验。

jquery验证插件有很多,实现的功能也基本相同。本文介绍的只是jquery验证插件中的一种jquery.validate

jquery.Validation是一款优秀的jquery插件,它能对客户端表单进行验证,并且提供了许多可以定制的属性方法,良好的扩展性。

1.jquery.validate插件功能

简单实现客户端信息验证,过滤不符合要求的信息

2.jquery.validate官方地址

官方地址:,有详细的插件使用说明

官方demo:

3.jquery.validate使用方法

1.引用js

rush:js;">

2.css样式,可自定义,简单的只需要添加error样式,也可使用官方demo中的样式。

rush:css;"> .error{ color:red; margin-left:8px; }

3.js代码

rush:js;"> $(document).ready(function() { // validate signup form on keyup and submit var validator = $("#signupform").validate({ rules: { firstname: "required",username: { required: true,minlength: 2 },password: { required: true,minlength: 5 },password_confirm: { required: true,minlength: 5,equalTo: "#password" },email: { required: true,email: true,},dateformat: "required",terms: "required" },messages: { firstname: "姓名不能为空",username: { required: "用户名不能为空",minlength: jQuery.format("用户名只少由 {0} 字符组成") },password: { required: "密码不能为空",minlength: jQuery.format("密码只少由 {0} 字符组成") },password_confirm: { required: "确认密码不能为空",minlength: jQuery.format("确认密码只少由 {0} 字符组成"),equalTo: "秘密与确认密码不一致" },email: { required: "邮箱不能为空",email: "邮箱格式不正确" },dateformat: "请选择性别",terms: " " },// the errorPlacement has to take the table layout into account errorPlacement: function(error,element) { if ( element.is(":radio") ) error.appendTo( element.parent().next().next()); else if ( element.is(":checkBox") ) error.appendTo ( element.next()); else error.appendTo( element.parent().next()); },// specifying a submitHandler prevents the default submit,good for the demo submitHandler: function() { alert("submitted!"); },// set this class to error-labels to indicate valid fields success: function(label) { // set as text for IE label.html("").addClass("checked"); },highlight: function(element,errorClass) { $(element).parent().next().find("." + errorClass).removeClass("checked"); } }); });

以上的代码只使用了插件提供的属性方法。也可以自定义验证方法。如

rush:js;"> $.validator.addMethod("checkUserName",function(value) {
//value为验证的值,对应于元素id

//方法代码

},'用户名格式不正确');

使用自定义方法也非常简单,只需要 元素id:”checkUserName”

4.使用的html

rush:xhtml;">
irstname" for="firstname">姓名用户名性别
<tr&gt;
  <td style="padding-right: 5px;"&gt;
    <input id="sex_men" name="dateformat" type="radio" value="0" />
    <label id="lbl_sex_men" for="dateformat_eu"&gt;男</label>
  </td&gt;
  <td style="padding-left: 5px;"&gt;
    <input id="sex_women" name="dateformat" type="radio" value="1" />
    <label id="lbl_sex_women" for="dateformat_am"&gt;女</label>
  </td&gt;
  <td&gt;
  </td&gt;
</tr&gt;
</tbody>
</table&gt;
</td&gt;

</tr>

<tr>
<td class="label"></td>
<td class="field" colspan="2">
<div id="termswrap">

</table>

更多验证方法的应用请查看

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐