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!
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');
}
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With