Tips for using jQuery validation

The jQuery validation plugin is very easy to use, the docs are pretty dang good, and the examples are top notch. However, there can be a few 'gotchyas' when working with the plugin.

First, if you're using the 'easy' validation method, use a form to wrap all of the fields you'd like to validate. The form doesn't have to have an action, but it should have a unique 'id' attribute.

Also, all of your form elements should have a 'name' attribute in addition to the 'id' attribute you'd normally use to reference them in the DOM. The 'name' attribute is normally only used when submitting form elements -- but it needs to be there for jQuery validation even if you don't plan on submitting the form.

<div id="content" style="padding: 10px;">
    <form id="frmTest" method="get">
        Lots of other content here<br />
        Lots of other content here<br />
        Lots of other content here<br />
        Lots of other content here<br />
        Lots of other content here<br />
        Lots of other content here<br />
        <input id="txtEmail" name="txtEmail" type="text" class="required email"/>
        <br />
        <input id="txtName" name="txtName" type="text" class="required" minlength="2"/>
        <br />
        Other content
        <br />
        <button id="btnValidate" type="button">Test validation</button>
    </form>
</div>

You can also use a custom 'error' CSS class. This can be useful when your CSS has already defined a class called 'error' (like Blueprint does) and you don't want to use that CSS class for form validation errors. jQuery validation uses the 'error' class by default. To override this, you can define a different CSS class to use:

label.invalid
{
    color: Red;
    font-style: italic;
    padding: 1px;
    margin: 0px 0px 0px 5px;
}

$(document).ready(function ()
{
    //  Bind validation rules
    $("#frmTest").validate({
        errorClass: "invalid"
    });

    //  Bind click handler:
    $("#btnValidate").click(function ()
    {
        if ($("#frmTest").valid())
            alert("Valid");
    });
});

If you need extra help with designing your app with Javascript, you can’t go wrong with this fantastic book from Douglas Crockford:


JavaScript: The Good Parts