我有一个简单的表格
<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");
关于JQuery 验证 - 自定义规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35408305/