Jquery Validation plug-in custom error placement

Mirko picture Mirko · Jun 3, 2010 · Viewed 66k times · Source

Using the jQuery Validation plug-in for the following form:

<form id="information" method="post" action="#">

            <fieldset>
                <legend>Please enter your contact details</legend>
                <span id="invalid-name"></span>
                <div id="id">
                    <label for="name">Name: (*)</label>
                    <input type="text" id="name" class="details" name="name" maxlength="50" />
                </div>

                <span id="invalid-email"></span>
                <div id="id">
                    <label for="email">Email: (*)</label>
                    <input type="text" id="email" class="details" name="email" maxlength="50" />
                </div>
            </fieldset>
            <fieldset>
                <legend>Write your question here (*)</legend>
                <span id="invalid-text"></span>
                <textarea  id="text" name="text" rows="8" cols="8"></textarea>


            <div id="submission">
                <input type="submit" id="submit" value="Send" name="send"/>
            </div>
            <p class="required">(*) Required</p>
            </fieldset>

             </form>

How can I place the errors inside the span tags? (#invalid-name, #invalid-email, #invalid-text)

I read the documentation about error placement but I did not get how it works. Is it possible to handle each single error and place it in the specified element?

Thank you

Answer

Stefan Morrow picture Stefan Morrow · Oct 28, 2010

You can also manually add error labels in places you need them. In my particular case I had a more complex form with checkbox lists etc. where an insert or insert after would break the layout. Rather than doing this you can take advantage of the fact that the validation script will evaluate if an existing label tag exists for the specified field and use it.

Consider:

<div id="id">
    <label for="name">Name: (*)</label>
    <input type="text" id="name" class="details" name="name" maxlength="50" />
</div>

Now add the following line:

<label for="name" class="error" generated="true"></label>