简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM