[英]JQuery Validation - custom rule
I have a simple form 我有一个简单的表格
<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>
The bottom radio controls a text input. 底部的收音机控制文本输入。 Initially this is hidden, and I do
最初这是隐藏的,而我确实
$('input:radio[name="reason[]"]').change(
function(){
if ($(this).is(':checked') && $(this).val() == 'Other') {
$('#other').css("display", 'block');
} else {
$('#other').css("display", 'none');
}
}
);
Defining rules for radio buttons is straight forward, I just need to make sure one is selected. 为单选按钮定义规则很简单,我只需要确保已选择一个即可。 I am having a few issues with a custom rule.
我在使用自定义规则时遇到了一些问题。 Essentially, if reasonThree is selected, I need to make sure they enter something into the text input which is at this point displayed.
本质上,如果选择了reasonThree,我需要确保它们在此时显示的文本输入中输入了一些内容。 At this moment, I am trying something like the following.
目前,我正在尝试以下操作。
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")
}
}
});
If they select the last radio button, how can I make sure they enter something into the text area? 如果他们选择了最后一个单选按钮,如何确定他们在文本区域中输入了什么内容?
Thanks 谢谢
There is no element with id [id='reasonFive']
. 没有id为
[id='reasonFive']
元素。 Try to change your custom method like this:- 尝试像这样更改您的自定义方法:
$.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.