最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JQuery validation-input text field to be required if checkbox checked - Stack Overflow

programmeradmin0浏览0评论

I have the following checkbox:

<input type="checkbox" id="startClientFromWeb" name="startClientFromWeb" data-bind="checked: StartClientFromWeb" />

and the following input text field:

<input id="mimeType" name="mimeType" data-bind= "value: MimeType" />

This is my js validation code:

 $("#franchiseForm").validate({
            rules: {
                mimeType: {
                    required: $("#startClientFromWeb").is(":checked")
                }
            }
        });

I want the mimeType input text field to be required only if checkbox is checked. For some reason the above is not working. I am quite new to javascript and jquery. Any help with working example will be greatly appreciated. Thank You!

I have the following checkbox:

<input type="checkbox" id="startClientFromWeb" name="startClientFromWeb" data-bind="checked: StartClientFromWeb" />

and the following input text field:

<input id="mimeType" name="mimeType" data-bind= "value: MimeType" />

This is my js validation code:

 $("#franchiseForm").validate({
            rules: {
                mimeType: {
                    required: $("#startClientFromWeb").is(":checked")
                }
            }
        });

I want the mimeType input text field to be required only if checkbox is checked. For some reason the above is not working. I am quite new to javascript and jquery. Any help with working example will be greatly appreciated. Thank You!

Share Improve this question asked May 21, 2012 at 13:55 MdbMdb 8,56822 gold badges65 silver badges100 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 12

You can add your own custom validation methods to handle things like this:

$.validator.addMethod("requiredIfChecked", function (val, ele, arg) {
    if ($("#startClientFromWeb").is(":checked") && ($.trim(val) == '')) { return false; }
    return true;
}, "This field is required if startClientFromWeb is checked...");


$("#franchiseForm").validate({  
        rules: {  
            mimeType: { requiredIfChecked: true }  
        }  
 });

Validation will not triger if input is disabled. You could use that fact - let textbox be required, but initially disabled, and enable it only when checkbox is checked.

$(function () {
   $('#startClientFromWeb').change(function () {
        if ($(this).is(':checked')) {
            $('#mimeType').removeAttr('disabled');                
        }
        else {
            $('#mimeType').attr('disabled', 'disabled');
        }
    });
});

The simpliest way which works:
rules : {mimeType:{required:"#startClientFromWeb:checked"}}, messages: {mimeType: {required: 'Repeat checked, To date required'}}

发布评论

评论列表(0)

  1. 暂无评论