Input validation with jQuery

The jQuery validation plugin provides ways to seamlessly enable client side input validation and allows you to dial the knob from basic – all the way up to fully customized validation rules.

Here is an example of a basic form validation which contains the html that we’ll use throughout our examples. One very important thing to note is that the “name” attribute is required for the validation to work!

<style>label.error { color: #ff0000; }</style>
<script>
    $(document).ready(function() {
        $('#registerForm').validate();
    })
</script>
<!-- validation classes: email, url, date, number, digits, creditcard -->
<form id="registerForm" class="myForm">
    <fieldset>
        <legend>Register</legend>
        <p>
            <label for="firstName">First Name:</label>
            <input id="firstName" type="text" name="firstName" class="required" title="Please enter a first name" />
        </p>
        <p>
            <label for="lastName">Last Name:</label>
            <input id="lastName" type="text" name="lastName" class="required" />
        </p>
        <p>
            <label for="email">Email:</label>
            <input id="email" type="text" name="email" class="required email" />
        </p>
        <p>
            <label for="acctNum">Account Number:</label>
            <input id="acctNum" type="text" name="acctNum" class="required number" />
        </p>
        <p>
            <label for="password">Password:</label>
            <input id="password" type="password" name="password" />
        </p>
        <p>
            <label for="cfmPassword">Confirm Password:</label>
            <input id="cfmPassword" type="password" name="cfmPassword"/>
        </p>
    </fieldset>
    <input type="submit" value="Submit" />
</form>

This is setup so when you hit the “Submit” button, it will first validate the form like so:

initial

But what if you’re posting the form via Ajax and also have multiple forms (possibly added dynamically) that all needs to be validated.  Well, you could loop through all of the forms and initiate validation manually:

<script>
    $(function() {
        $('#btnAjaxSubmit').click(function () {
            var pass = true;
            $(".myForm").each(function(index, form) {
                if (!$(form).valid()) { 
                    pass = false;
                }
            });

            if (pass) {
                alert("Ajaxed!");
            } else {
                 alert("Validation Failure!!!!");
            }
        });
    });
</script>

One more thing you could do is change the default error messages.  And if you’ve applied only one validation class (e.g., required) for an input, then simply add a title attribute to the input field and jQuery validation will use that as the error message:

<input id="firstName" type="text" name="firstName" class="required" title="Please enter a first name" />

But lets say if you have both “required” and “email” applied to an input, then the message that you put in the title attribute wont make much sense, since you probably want to display different error messages to let the user know what is required.  Here is an example for doing just that:

$('#registerForm').validate({
            rules: {
                password: {
                    required: true
                },
                cfmPassword: {
                    equalTo: "#password"
                }
            },
            messages: {
                email: {
                    required: 'Please enter your email address',
                    email: 'Not a valid email address'
                }
            } 
        });

The messages section is where you would define custom error messages for each type of validation that you’ve applied to the input, and it is labeled using the “name” attribute of the input field.  In the example above I’m also applying validations using the rules section.  If you don’t like cluttering up your html inputs with different class names, then this is a route that you could take.  And here is our final form:

customValidation

One other option is to extend the jQuery validator messages to include your own:

jQuery.extend(jQuery.validator.messages, { required: “custom required message”,  number: “custom message”});

References: API Documentation