[英]jQuery Validation checkbox custom value rule
是否可以使用jQuery Validation插件在復選框中檢查自定義值(除True / False外)?
例如 :
<input id="test" type="checkbox" name="test" value="something">
我找不到一種方法來檢查“某物”是否有價值。 出於特定原因,我不能僅使用“ true”作為值。
嘗試這個 :
$('#test').attr('value');
您可以在custo驗證方法中使用它。
聲明自定義規則:
$.validator.addMethod("myRule", function(value, element) {
var v = element.attr('value');
if(v === 'something') {
return true;
}
return true;
}, $.validator.format('my message') );
要在字段上設置自定義規則:
$('#form').validate({
rules : {
test : {
myRule : true
}
}
});
采用:
$("#test").val()
或者,如果您想在變更事件中獲得價值,那么:
演示: http : //jsfiddle.net/qsDn5/16/
$("#test").change(function(){
alert(this.value);
});
您可以使用addMethod添加規則,然后根據測試結果返回一個布爾值,如下所示:
// Add Custom Method
$.validator.addMethod('someTest', function(value, element){
return 'something' === value;
}, $.validator.format('Custom Message'));
// Use Custom Method
$('#theForm').validate({
rules: {
checkBoxField: {
someTest: true
}
...
});
我希望這有幫助!
試試Jquery Validation插件,
<form id="myform">
<input type="checkbox" name="test[]" />x
<input type="checkbox" name="test[]" />y
<input type="checkbox" name="test[]" />z
<input type="submit" />
</form>
<a id="docs" href="http://docs.jquery.com/Plugins/Validation" target="_blank">Validation Documentation</a>
碼:
$(document).ready(function () {
$('#myform').validate({ // initialize the plugin
rules: {
'test[]': {
required: true,
maxlength: 2
custommethod: true
}
},
messages: {
'test[]': {
required: "You must check at least 1 box",
maxlength: "Check no more than {0} boxes"
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
});
更新: http : //jsfiddle.net/aJBK9/2/
在jquery驗證中使用addMethod,
$.validator.addMethod("custommethod", function(value, element) {
if (value==="something"){return true;}
return false;
}, "Value must be some thing");
檢查此演示鏈接http://jsfiddle.net/aJBK9/1/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.