I am validating a form using jQuery validate. Form has 3 fields. 1 textarea, 1 checkbox and 1 input type text. I want to validate form dynamically i.e. when user has enter some value in input type text then checkbox and textarea are not required but if user not enter value in it both are required. Below code I tried :
$("#form").validate({
rules: {
inputTypeText: {required: true},
inputTypeCheckbox: {required: false},
textarea: {required: false},
},
messages: {
inputTypeText: "This field is required",
inputTypeCheckbox: "This field is required",
textarea: "This field is required",
},
submitHandler: function(form) {
form.submit();
}
});
$('#inputTypeText').keyup(function(){
if($(this).val()==''){
$('input[name="inputTypeText"]').rules('add',{required: false});
$('textarea[name="inputTypeCheckbox"]').rules('add',{required: true});
$('input[name="textarea"]').rules('add',{required: true});
}else{
$('input[name="inputTypeText"]').rules('add',{required: true});
$('input[name="inputTypeCheckbox"]').rules('add',{required: false});
$('textarea[name="textarea"]').rules('add',{required: false});
}
});
It throws error as below screenshot.
Please help me in this. Thank you in advance.