这是我的要求:我有一堆无线电盒选择(工作流程类型)。如果选择了其中一个无线电(即选择了一种特定类型的工作流),我想对其进行自定义验证。这是我尝试过的,但表现不佳。有什么帮助吗?
jQuery部分:
$(document).ready(function() {
// this part is to expand the child radio selection if particular parent workflow selected
$("#concernedDirectorChoice").hide();
$("input[name^=workflowChoice]").change( function (){
if($(this).attr("class")=='chooseDir'){
$("#concernedDirectorChoice").show();
}else{
$("#concernedDirectorChoice").hide(); }
});
// FORM VALIDATION
$.validator.addMethod("dirRequired", function(value, element) {
return this.optional(element) || ($("input[name^=rdDir:checked]").length);
}, "That particular workflow requires a Director to be chosen. Please select Director");
$("#contExpInitiateForm").validate({
debug:true
,rules:{
RenewalNo: {required: true, number: true},
chooseDir: {dirRequired: true},
workflowChoice: {required: true} }
,errorPlacement: function(error, element) {
$('.errorMessageBox').text(error.html()); }
});
});
HTML表单部分:
<!-- Pick type of workflow -->
<table class="hr-table" >
<tr> <td class="hr-table-label " colspan=2 >Pick Workflow Type</td> </tr>
<tr>
<td> <input type="radio" name="workflowChoice" value="1"> </input> </td>
<td> Workflow 1 </td>
</tr>
<tr>
<td> <input type="radio" name="workflowChoice" value="2" class="chooseDir"> </input> </td>
<td> Workflow 2 (Dir selection required) </td>
</tr>
<tr>
<td> <input type="radio" name="workflowChoice" value="3"> </input> </td>
<td> Workflow 3 </td>
</tr>
</table>
<!-- Pick Director for Workflow type 2 -->
<table id="concernedDirectorChoice" name="concernedDirectorChoice" >
<tr><td class="hr-table-label" colspan=2 > Choose Concerned Director</td></tr>
<tr>
<td><input type="radio" value='Dir1' name="rdDir" /></td>
<td>Director 1</td>
</tr>
<tr>
<td><input type="radio" value='Dir2' name="rdDir" /></td>
<td>Director 2</td>
</tr>
<tr>
<td><input type="radio" value='Dir3' name="rdDir" /></td>
<td>Director 3</td>
</tr>
</table>
答案 0 :(得分:1)
您的主要问题可能是选择器,:checked
需要在attirubte([]
)选择器旁边,因此input[name^=rdDir:checked]
应为input[name^=rdDir]:checked
。
如果选择<input type="radio" class="chooseDir" />
中的任何一个,那么从您的标记看起来(对我而言)您需要它,因此无论如何都需要将其更改为.chooseDir:checked
。
此外,规则对应为nameOfElement: { rules}
,因此您需要实际需要chooseDir
而不是rdDir
。
尽管如此,您也可以在没有自定义方法的情况下执行此操作(如果您未在多个位置使用它,在这种情况下我会坚持使用自定义方法),因为required:
可以选择器而不仅仅是true
/ false
。如果选择器找到任何东西,则需要它,如果不是,则不需要它。
以上是上面的所有内容,因此您可以看到整个图片看起来像:
$("#contExpInitiateForm").validate({
debug:true
,rules:{
RenewalNo: {required: true, number: true},
rdDir: {required: ".chooseDir:checked"},
workflowChoice: {required: true} }
,messages:{
rdDir: "That particular workflow requires a Director to be chosen. Please select Director" }
,errorPlacement: function(error, element) {
$('.errorMessageBox').text(error.html()); }
});
在上面的代码中,如果选择了任何rdDir
单选按钮,则需要class="chooseDir"
单选按钮列表,如果需要并且未填写,则会显示提供的消息。