Problem

When adding or tweaking validation rules on forms sometimes I’ve observed that the validation messages will either not appear at all, or will appear only on some fields and not others. When this happens it leaves me wondering, where is my jQuery validation message?

<input type="text" id="city" value="Portland" class="required" />
<input type="text" id="state" value="OR" class="required" />

Quick Solution

Double check that each of the fields in question has a name attribute specified.

<input type="text" id="city" name="city" value="Portland" class="required" />
<input type="text" id="state" name="state" value="OR" class="required" />

Explanation

Back in the olden days of the web, our forms were submitted to a server for processing (via get or post as specified in the form tag). The data captured in the field elements of the form were referenced by their name (you guessed it, that’s in the name attribute).

With the growing adoption of AJAX, the fields are commonly referenced client side via their ID. The data is bundled up as JSON objects which are submitted to the server for processing. It is not uncommon to find forms in this type of application where a field’s name attribute has been omitted in favor of the ID.

While one could argue that the name attribute should be specified on every form field every time to maintain standards compliance, the simple truth of the matter is that not every form you may cross will have this. So rather than assuming that the name attribute has been specified save yourself a headache and double-check.

The jQuery validation library requires that fields have a name specified. These names are referenced in the label element which is generated to wrap the error message (by default). This is probably a requirement to allow for support of legacy-type form submission, but regardless of why it’s required this little bugger has bit me more than once.

One strange piece of behavior that I’ve observed which can throw you when trying to determine a cause for a disappearing validation message is that when you have a form with several elements, the first of a given type (input, select, etc) may work while subsequent fields of that type do not. Again, this is most often caused by missing name attributes. In the absence of a name to uniquely identify the field, the validation library will simply apply the validation to the first field of that type.

Extensive documentation on the jQuery validation plugin is available on the plugins website.

This entry was posted on February 27, 2013.