9

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!

3 Answers 3

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 }  
        }  
 });
Sign up to request clarification or add additional context in comments.

2 Comments

I tried your code. It gives me the following error: "Expected: :" for this line: mimeType: { requiredIfChecked } Can You please give the example in Fiddle ?
Thank You! The problem was that I am applying the validations on $(document).ready and the value of the checkbox is always false. Now I apply the validations after ko.applyBindings call and it works as expected. Anyway thank You for your help.
2

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');
        }
    });
});

1 Comment

I have not disabled the #mimeType input.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.