查看文章
 
jQuery Validation 表单验证
2008-11-11 18:16

以前我做客户端的检测都是一个属性写一个函数,我自己也觉得很不好,但也没有更好的办法,今天在一人blog里看到介绍jQuery的插件Validation,看了下,真的感觉很不错。jQuery提供的参数文档,这插件的作者提供的一些DEMO.
$.validator.setDefaults({
debug: true
});
设置默认的状态为debug,这样用户的数据就不会提交了。

接下来是一段比较长的代码,但是不用怕,因为真的挺简单的//当页面载入完成时,执行以下动作
$().ready(function() {
$("#myform").validate({
//设置默认的状态为keyup,也可以设置为blur
event: "keyup",
//设定规则
rules: {
//对应id为'username'的input
username: {
//必填项
required: true,
//最多和最少的字符数
rangeLength:[4,16]
},
mail: {
required: true,
//声明这是一个电子邮件
email: true
},
password: {
required: true,
//最少4个字符
minLength: 4
},
confirm_password: {
required: true,
minLength: 4,
// 与哪个等同,这里是id为password的input等同
equalTo: "#password"
},
agree: "required"

},

//这里是与规则对应的错误代码
messages: {
username: {
//如果用户名为空,则显示下面的信息
required: '请输入用户名',
//如果字符串的长度不符合,则显示下面的信息
rangeLength: '用户名必须在4-16个字符之间'
},
password: {
required: '请输入密码',
minLength: '密码必须大于4个字符'
},
confirm_password: {
required: '请确认你的密码',
equalTo: '两次密码输入不一致',
minLength: '密码必须大于4个字符'
},
agree: '请同意我们的条款',
mail: '请输入有效的E-MAIL帐户'
},

//可选项,当用户的输入符合我们设定的规则时显示
success: function(label) {
label.html('√').addClass("success");
}
});
});
</script>


代码里写了注释,看起来应该还是比较容易理解的吧,最后就是一个form

<form id="myform" action="index.html" method="get" >
<fieldset>
<legend>用户注册界面</legend>
<p><label for="username">用户名:</label>
<input type="text" name="username" id="username" />
<p><label for="mail">电子邮件地址:</label>
<input type="text" name="mail" id="mail" />

<p><label for="password">密码:</label>
<input type="password" name="password" id="password" />

<p><label for="confirm_password">密码确认:</label>
<input type="password" name="confirm_password" id="confirm_password" />

<p><label for="agree">请同意我们的条款:</label><input type="checkbox" name="agree" id="agree" />


<div id="submit"><input type="submit" value="Submit" /></div>
</fieldset>
</form>

类别:Java Util||添加到搜藏 |分享到i贴吧|浏览(4776)|评论 (0)
 
最近读者:
 
网友评论:
发表评论:
姓 名:
网址或邮箱: (选填)
内 容:
     

   
帮助中心 | 空间客服 | 投诉中心 | 空间协议
©2012 Baidu