[英]jQuery validation custom method didn't work
我在jQuery驗證器上添加了這樣的方法
$.validator.addMethod(
'myEqual',
function (value, element) {
return value == element.value; // this one here didn't work
},
'Please enter a greater year!'
);
$.metadata.setType("attr", "validate");
$("#educationForm").validate({
showErrors: function(errorMap, errorList) {
this.defaultShowErrors();
},
errorPlacement: function(error, element) {
error.appendTo( element.parent("td").next("td") );
},
/*success: function(label) {
label.text("ok!").addClass("success");
},*/
rules: {
txt_end: {
required: true,
myEqual: "#txt_begin"
}
},
submitHandler: function() {}
});
表格看起來像這樣
<div id="wrapper_form">
<form id="educationForm" name="educationForm" method="post" action="">
<table width="500" border="0">
<tr>
<td width="100">Period:</td>
<td width="200"><input type="text" name="txt_begin" id="txt_begin" size="8" maxlength="4" class="required year ui-widget-content ui-corner-all" /> to
<input type="text" name="txt_end" id="txt_end" size="8" maxlength="4" class="required year ui-widget-content ui-corner-all" /></td>
<td width="200"></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="btn_submit" id="btn_submit" value="Submit" class="ui-button ui-state-default ui-corner-all" />
<input type="button" name="btn_cancel" id="btn_cancel" value="Cancel" class="ui-button ui-state-default ui-corner-all" />
</td>
<td> </td>
</tr>
</table>
</form>
</div>
但是為什么我添加的自定義方法不起作用?
return value == element.value; // this one here didn't work
它總是返回true為任何值我在這里錯過了什么嗎? 我沒有使用內置方法,因為稍后在表單中,我將需要編寫另一種方法來檢查是否大於或等於和小於或等於(“> =”和“ <=”)。等於和降低或等於,方法是將“ ==”替換為“> =”或“ <=”
閱讀您的代碼后,我發現您正在使用自定義方法嘗試比較兩個文本輸入,正在將參數傳遞給驗證器: myEqual: "#txt_begin"
。
為此,您必須處理addMethod回調函數的第三個參數:
$.validator.addMethod('myEqual', function (value, element, param){// param will
return value == $(param).val(); // have
}, 'Message'); // "#txt_begin"
為什么不使用Validate插件提供的“ equalTo”方法?
rules {
txt_begin : 'required' ,
txt_end: { equalTo: '#txt_begin' }
}
您不必為txt_end放置必填項,因為它必須等於txt_begin且txt_begin是必填字段。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.