jquery.validate中文API和应用实例(三)高级验证基础

中文版jquery.validate API下载地址: jQuery_validateAPI中文.rar

在前面说到的简单验证中,使用起来非常简单,有些傻瓜式的味道,但毕竟有些内置规则不能使用。但要想做到灵活运用,还是需要通过JS编码来完成。这样不但所有的内置规则可以使用,而且我们还可以自定义验证规则。以下实例我从易到难逐个列出:

1.编写JS的简单方法

仍以登录验证为例:

<script type="text/javascript" language="javascript" src="http://www.cnblogs.com/Scripts/jquery-1.4.1.min.js"></script>
<script type="text/javascript" language="javascript" src="http://www.cnblogs.com/Scripts/jquery.validate.min.js"></script>
<h2>Validate-High</h2>
<form action="" id="loginForm" method="post">
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
<input type="text" id="UserEmail" />
</td>
</tr>
<tr>
<td>
<input type="password" id="Password" />
</td>
</tr>
<tr>
<td>
<input type="submit" value="submit"/>
</td>
</tr>
</table>
</form>
<script language="javascript" type="text/javascript">

$(document).ready(function () {
var validateOpts
= {
rules: {
UserEmail: {
required:
true,
email:
true
},
Password: {
required:
true 
}
},
messages: {
UserEmail: {
required:
"请输入邮箱地址",
email:
"邮箱地址不正确"
},
Password: {
required:
"请输入密码" 
}
}
};
$(
"#loginForm").validate(validateOpts);
});
</script>

我们只需设置validate的参数即可。

2.equalTo的使用,一般在注册时会用到

<script type="text/javascript" language="javascript" src="http://www.cnblogs.com/Scripts/jquery-1.4.1.min.js"></script>
<script type="text/javascript" language="javascript" src="http://www.cnblogs.com/Scripts/jquery.validate.min.js"></script>
<h2>
ValidateHigh
</h2>
<form action="" id="loginForm" method="post">
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
        <input type="text" id="UserEmail" /> 
</td>
</tr>
<tr>
<td>
         <input type="password" id="Password" />
</td>
</tr>
<tr>
<td>
<input type="password" id="RePassword" />
</td>
</tr>
<tr>
<td>
<input type="submit" value="submit"/>
</td>
</tr>
</table>
</form>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
var validateOpts
= {
rules: {
UserEmail: {
required:
true,
email:
true
},
Password: {
required:
true
},
RePassword: {
equalTo:
"#Password"
}
},
messages: {
UserEmail: {
required:
"请输入邮箱地址",
email:
"邮箱地址不正确"
},
Password: {
required:
"请输入密码"
},
RePassword: {
equalTo:
"两次输入密码必须相同"
}
}
};
$(
"#loginForm").validate(validateOpts);
});
</script>

3.required(dependency-callback)的使用,绿色字体。

var validateOpts = {
rules: {
age: {
required:
true,
min:
3
},
parent: {
required: function (element) {
return $("#age").val() < 13;
}
}
}
}

4.自定义规则,使用addMethod方法,如下:

//方法接收三个参数(value,element,param)
    
//value是元素的值,element是元素本身 param是参数,我们可以用addMethod来添加除built-in Validation methods之外的验证方法
    
//比如有一个字段,只能输一个字母,范围是a-f,写法如下
$.validator.addMethod("af", function (value, element, params) {
if (value.length >1) {
returnfalse;
}
if (value >=params[0] && value <=params[1]) {
returntrue;
}
else {
returnfalse;
}
},
"必须是一个字母,且a-f");

这样我们就可以在rules中加上这个规则,如下

    var validateOpts = {
rules: {

selectorId: {
af: ["a","f"]//
如果只有一个参数,直接写,如果af:"a",那么a就是这个唯一的参数,如果多个参数,用在[]里,用逗号分开
}
}
    }
另外,经过试验,在Json方式中,我们可以使用af:['a','f'],这个验证可以起作用,在class方式中,在某个元素上增加af='af',验证也可以起到作用。

5.ajax验证,使用remote

remote: {
url:
"CheckEmail",
type:
"post",
dataType:
"json"
}

如果我们验证的方法是返回Boolean类型,这个方法是没有问题的。但很多时候我们可能返回的信息会更多,或者返回其它类型,这时我们可以重新定义一个新的remote方法,示例如下(返回一个Json对象):

$.validator.addMethod("jsonremome", function (value, element, param) {
if (this.optional(element))
return"dependency-mismatch";

var previous
=this.previousValue(element);
if (!this.settings.messages[element.name])
this.settings.messages[element.name] = {};
previous.originalMessage
=this.settings.messages[element.name].remote;
this.settings.messages[element.name].remote = previous.message;

param
=typeof param =="string"&& { url: param} || param;

if (previous.old !== value) {
previous.old
= value;
var validator
=this;
this.startRequest(element);
var data
= {};
data[element.name]
= value;
$.ajax($.extend(
true, {
url: param,
mode:
"abort",
port:
"validate"+ element.name,
dataType:
"json",
data: data,
success: function (response) {
validator.settings.messages[element.name].remote
= previous.originalMessage;
//var valid = response === true;
var valid = response.Result ===true;
if (valid) {
var submitted
= validator.formSubmitted;
validator.prepareElement(element);
validator.formSubmitted
= submitted;
validator.successList.push(element);
validator.showErrors();
}
else {
var errors
= {};
//var message = (response.Message || validator.defaultMessage(element, "jsonremote"));
var message = response.Message ||"远程验证未通过";
errors[element.name]
= $.isFunction(message) ? message(value) : message;
validator.showErrors(errors);
}
previous.valid
= valid;
validator.stopRequest(element, valid);
}
}, param));
return"pending";
}
elseif (this.pending[element.name]) {
return"pending";
}
return previous.valid;

});

服务器端方法如下(MVC中):

public JsonResult CheckEmail(string UserEmail)
{
returnnew JsonResult { Data =new { Result =false, Message="Please change the filed" } };
}

我们就可以使用jsonremote来取代remote方法了。当然,remote方法依然可以使用。

6.错误显示规则

var validateOpts = {
wrapper:
"div",// default has no wrapper
errorClass: "invalid", // the default value is error
errorElement: "em", // default value is lable
errorLabelContainer: "#messageBox", // to gather all the error messages
}
posted @ 2011-03-12 21:51  Wang Juqiang  阅读(4855)  评论(3编辑  收藏  举报