Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Validate Plugin - Validate Hidden Field by Name

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?

  • jQuery Validate Plugin - How to create a simple custom rule?
  • jquery validate - valid if hidden field has a value

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.

like image 940
James Hill Avatar asked Oct 08 '22 21:10

James Hill


1 Answers

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');
            }
        }
    });
});
like image 151
ShankarSangoli Avatar answered Oct 12 '22 11:10

ShankarSangoli