jQuery.validator.addMethod自定义验证方法

在开发中用到了jQuery的validate控件,有时需要自定义验证方法。我们可以通过jQuery.validator.addMethod()来实现,下面是例子:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="../css/main.css" rel="stylesheet" type="text/css" />
<link href="../js/ligerUI/skins/Aqua/css/ligerui-all.css" rel="stylesheet" type="text/css" />
<!-- 引入JS库文件 -->
<script src="../js/jquery.min.js" type="text/javascript"></script>
<script src="../js/ligerUI/js/ligerui.min.js" type="text/javascript"></script>
<script src="../js/tablecolor.js" type="text/javascript"></script>
<script src="../js/jquery-form/jquery.form.js" type="text/javascript"></script>
<script src="../js/jquery-validation/jquery.validate.min.js" type="text/javascript"></script>
<script src="../js/jquery-validation/messages_cn.js" type="text/javascript"></script>

<script type="text/javascript">
<!--
$(function() {

//保存
$("#appEdit_btok").click(function () {
$("#appEdit_Form").submit();
});

//自定义评语内容验证方法
jQuery.validator.addMethod("levelLimit",function(value, element){
var returnVal = false;
var level = $("#code").attr("level");
if(level=="1" || level=="0"){
returnVal = true;
}
return returnVal;
},"level不能为2!");
$("#appEdit_Form").validate({
rules : {
"code" : {
required : true,
number : true,//期望的是true,如果为false则展示提示信息
levelLimit : true//期望的是true,如果为false则展示提示信息
}
},
messages : {
"code" : {required : "请输入务编码!",
number : "请输入数字!"
}
},
errorPlacement: function( lable, element ){
element.ligerHideTip();
element.parent().ligerTip({ content: lable.html(), target: element[0] });
},
success : function( lable ){
lable.ligerHideTip();
lable.remove();
},
submitHandler: function(formTar){
var serialStr = $("#appEdit_Form").serialize();
var urlStr = './appIndex.htm?actionMethod=addAppInfo';
$.ajax({
type:'post',
url:urlStr,
data:serialStr,
success:function(redata){
if (redata ==1) {
alert( '操作成功!');
}else{
alert('失败提示', '操作失败!');
return;
}
}
});
}
});
});

//-->
</script>
</head>

<body >
<div class="right-body" >
<form method="post" action="javascript:void" id="appEdit_Form" >
<table style="width:400px;" border="0" cellpadding="0" cellspacing="0"
class="viewdatagrid">
<tbody>
<tr>
<th width="160">编码:</th>
<td width="0" ><input id="code" name="code" type="text" style="width: 240px" value="" level="2"/>
</td>
</tr>
</tbody>
</table>

<div class="btn-view-block">
<div class="toolbar">
<ul>
<li>
<a href="javascript:void 0;" class="save" id="appEdit_btok" name="appEdit_btok" ><span>保存</span></a>
</li>
<li>
</ul>
</div>
</div>
</form>
</div>
</body>
</html>

posted @ 2019-07-17 14:37  旧巷里的旧少年  阅读(3124)  评论(1编辑  收藏  举报