Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 674
Mdb Avatar asked May 21 '12 13:05

Mdb


Video Answer


2 Answers

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 }  
        }  
 });
like image 160
ShaneBlake Avatar answered Oct 25 '22 14:10

ShaneBlake


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');
        }
    });
});
like image 42
archil Avatar answered Oct 25 '22 15:10

archil