gipinani
gipinani

Reputation: 14398

jQuery Validate plugin not validating an element that's not a form input

I need to validate with jQuery Validation Plugin a combobox component: jqxComboBox. This component is applied on a div. So defining

<div id="component_id" />

$( "#component_id" ).jqxComboBox({...});

$("#component_id" ).rules( "add", {
    required: true,                  
    messages:{
        required: "Field is required"
    }
});

throws the following exception: Cannot read property 'nodeType' of undefined. I think it should due to the fact that I'm applying validation rules on a div.

This component generate an input type hidden to hold selected value. I have also tryed to apply validation rules on that hidden component, but this do not works: form is submitted also when hidden has no value.

$('input[type=hidden][name=myName]').rules( "add", {
    required: true,                  
    messages:{
        required: "Field is required"
    }
});

Can someone please give me some hints on how to solve this?

Upvotes: 1

Views: 1900

Answers (1)

Sparky
Sparky

Reputation: 98718

Quote OP:

"I need to validate with jQuery Validation Plugin a combobox component: jqxComboBox. This component is applied on a div."

As you learned, you cannot use jQuery Validate to validate a div. You can only validate input, select and textarea elements that are within a <form> container.

Quote OP:

"This component generate an input type hidden to hold selected value. I have also tryed to apply validation rules on that hidden component, but this do not works: form is submitted also when hidden has no value."

Putting the value inside a hidden input element is an acceptable workaround.

However, by default, the jQuery Validate plugin will ignore all hidden input elements. Simply change the ignore option to [] in order to ignore "nothing". Set the ignore option inside your .validate() call along with any/all of your other options.

$('#yourform').validate({
    // your other options, rules and callbacks,
    ignore: []  // <- ignore nothing - validate hidden elements
});

Documentation: http://jqueryvalidation.org/validate/#ignore

Upvotes: 1

Related Questions