[英]JQuery Validation - custom rule
我有一個簡單的表格
<form role="form" id="my_form" class="form-horizontal">
<label class="radio">
<input type="radio" name="reason[]" id="reasonOne" value="1"> Something
</label>
<label class="radio">
<input type="radio" name="reason[]" id="reasonTwo" value="2"> Something else
</label>
<label class="radio">
<input type="radio" name="reason[]" id="reasonThree" value="Other"> Other
</label>
<input type="text" name="reason[]" placeholder="Please specify" id="other" class="form-control">
</form>
底部的收音機控制文本輸入。 最初這是隱藏的,而我確實
$('input:radio[name="reason[]"]').change(
function(){
if ($(this).is(':checked') && $(this).val() == 'Other') {
$('#other').css("display", 'block');
} else {
$('#other').css("display", 'none');
}
}
);
為單選按鈕定義規則很簡單,我只需要確保已選擇一個即可。 我在使用自定義規則時遇到了一些問題。 本質上,如果選擇了reasonThree,我需要確保它們在此時顯示的文本輸入中輸入了一些內容。 目前,我正在嘗試以下操作。
jQuery.validator.addMethod('customrule', function() {
if($("input[id='reasonFive']:checked")) {
if(('#other').val().length == 0) {
return false;
} else {
return true;
}
}
return false;
}, 'Please input a reason' );
var validator = $("#my_form").validate({
rules: {
'reason[]': {
required: true,
customRule: true
}
},
messages: {
'reason[]': {
required: jQuery.validator.format("Please select an option")
}
}
});
如果他們選擇了最后一個單選按鈕,如何確定他們在文本區域中輸入了什么內容?
謝謝
沒有id為[id='reasonFive']
元素。 嘗試像這樣更改您的自定義方法:
$.validator.addMethod("customRule",function(value,element){
if($('#reasonThree').is(':checked')){
return $('#other').val().trim().length>0;
}else{
return true;
}
},"Please input a reason");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.