Primary Question
I'm new to the jQuery validate plugin. I need to validate hidden fields that are being added and removed dynamically and that share the same name. Example markup:
<input type="hidden" name="hdnItemID" value="123" />
<input type="hidden" name="hdnItemID" value="987" />
Basically, I need to know if any elements exist that have the name hdnItemID
. If they exist, the validation should be successful, else, the validation should fail.
if($("input[name='hdnItemID']").length > 0) {
//Form is valid
}
else {
//Form is invalid
}
I've looked at a few questions that seem close, but they don't seem to fit the bill. Any suggestions?
Secondary Question
Assuming that what I'm asking is possible, how would I specify where the validation message is displayed? Currently, I'm placing an asterisk by each required element when the validation fails. I'd like to continue to do that, but place the validation message for the hidden fields by the submit button.
Use submitHandler
event of the plugin to check if the hidden field exists or not. You can then conditionally submit the form. Try this.
$(function() {
$('#form1').validate({
submitHandler: function(form) {
if($("input[name='hdnItemID']").length > 0) {
//Form is valid
form.submit();
}
else {
//Form is invalid
alert('form data invalid');
}
}
});
});
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