jQuery.validity Guide & Documentation


Table of Contents:


Introduction:

jQuery.validity is a plugin designed to aid in the configuration of clientside form-validation. Validity was concieved with three goals:

  1. Easy Setup: Validity employs the principle of Convention Over Configuration to aid in keeping code manageable and semantic. Very little work is required to enable Validity for a page.
  2. Unobtrusive JavaScript: Using Validity will have little to no effect on the semantics of your markup. Additionally, Validity will degrade gracefully and leave no residuals in browser environments where JavaScript is disabled or unsupported.
  3. Customizable Appearence: Validity is an effort to deliver a solid core-library of validation tools that can be used in any web-design. Therefore, in order to be truly versatile, validation logic is separated from the way it displays errors. With Validity, you, the developer, have full control of error message handling and adapting it to the design of your page.

In style, validity makes use of jQuery's selector engine and follows its pattern of method chaining. If you know jQuery, then learning to use validity will be easy.


Setup:

In order to use Validity on a page, you will need to import the jQuery JavaScript library as well as jQuery.validity itself. Additionally, you will need to import the CSS styles for the error handling.

As a simple example suppose we start with the following HTML document with a simple form:

<html>
    <head>
        <title>Simple</title>
    </head>
    <body>
        <form method="get" action="simple.htm">
            Number of Vehicles:
            <input type="text" id="vehicles" name="vehicles" title="Vehicle Count" />
            <br /><br />
            Date of birth:
            <input type="text" id="dob" name="dob" title="Birthday" />
            <br /><br />
            <input type="submit" />
        </form>
    </body>
</html>
            

As you can see, there is no validation logic attached to the form. To import Validity we add the following code to the document's head.

<link type="text/css" rel="Stylesheet" href="jquery.validity.css" />

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.validity.js"></script>

<script type="text/javascript">
    // Select all of the forms on the page (in this case the only one)
    // and call 'validity' on the result.
    $(function() { 
        $("form").validity(function() {
            
        });
    });
</script>
            

Once jQuery, jQuery.validity and the validity styles are imported we can specify the validation logic using the validity method. Normally, this the validity method is called on jQuery objects of HTML forms and accepts a function as argument. As you can see, in the code above, a jQuery selector finds the form and then the validity method is called with an empty anonymous function as argument.

Inside the function argument we can specify the validation code.

Let's say that we want to require both of the fields. Also, we want to restrict the first field to be in the form of a number between 4 and 12. The second field will need to be a date and that date will have to be at some point in the past.

Validation methods are covered in greater detail later on in this document, but for now we can specify validation with the following use of the 'validity' method.

$("form").validity(function() {
    $("#vehicles")                      // The first input:    
        .require()                          // Required:
        .match("number")                    // In the format of a number:
        .range(4, 12);                      // Between 4 and 12 (inclusively):
    
    $("#dob")                           // The second input:
        .require()                          // Required:
        .match("date")                      // In the format of a date:
        .lessThanOrEqualTo(new Date());     // In the past (less than or equal to today):
});
            

That's all of the code that needs to be written to have a form validated by validity. Putting it all together, the interactive example below is produced.

[View Source]
<html>
    <head>
        <title>Simple</title>
        <link type="text/css" rel="Stylesheet" href="../../jquery.validity.css" />
        <script type="text/javascript" src="../../jquery.js"> </script>
        <script type="text/javascript" src="../../jquery.validity.js"> </script>
        <script type="text/javascript">
            $(function() { 
                $("form").validity(function() {
                    $("#vehicles")
                        .require()
                        .match("number")
                        .range(4, 12);
                    
                    $("#dob")
                        .require()
                        .match("date")
                        .lessThanOrEqualTo(new Date());
                });
            });
        </script>
    </head>
    <body>
        <form method="get" action="simple.htm">
            Number of Vehicles:
            <input type="text" id="vehicles" name="vehicles" title="Vehicle Count" />
            <br /><br />
            Date of birth:
            <input type="text" id="dob" name="dob" title="Birthday" />
            <br /><br />
            <input type="submit" />
        </form>
    </body>
</html>
                

Note: As of versiom 1.0.2+ you'll also need to put the arrow.gif image in the same directory as the stylesheet. (Otherwise the label output mode will not render correctly. See Label Output Mode Styles.)


Assigning Validation:

There are multiple ways to assign validation logic to a form.


The Validity Method

The validity method is defined on all jQuery objects, however it will only effect form elements. You may use it to select one or more forms and register the validation for each. There are two argument types that the method will accept: a function and a string.


Using a Function Argument

In almost all cases your argument into the validity method will be a function. Within the function you will call the validator methods.

The advantage of using a function argument for validation lies in your access to the jQuery selector engine for specifying rules.

For Advanced Users: the other advantage to function arguments is your ability to use JavaScript control structures (such as if...else blocks, iterators, etc.). In other words, the function passed into the validity method is executed just like any other JavaScript function. If your validation rules are conditional, nonlinear or otherwise complicated you can write whatever logic you need to. An example of a conditional validation scenario is below with the checkbox.


Basics

A simple validation scenario allows you to simply select individual inputs and setup validation on each. For example:

$('#my-form').validity(function() {

    // Required and has to be a number.
    $("#text-box-one")
        .require()
        .match("number");
    
    // Not required, but it has to be a date
    $("#text-box-two")
        .match("date");
        
});
            

You may also take advantage of the selector engine and validate several inputs with a single statement. For instance, if a page has several inputs that need to represent percentages, and that all need to add up to 100%, then the following code may be appropriate.

$('#my-other-form').validity(function() {

    // All of the interesting inputs will be under a percentage class, so:
    $(".percentage")
        .require()          // Each is required 
        .match("number")    // Each must be numeric
        .sum(100);          // The sum of all of them should be 100%.
        
});
            

Furthermore, you can use JavaScript control structures to conditionally validate. In the following interactive example, an if...then structure is used to require an email input only if the checkbox is checked.

[View Source]
<html>
    <head>
        <title>Conditional</title>
        <link rel="Stylesheet" type="text/css" href="../../jquery.validity.css" />
        <script type="text/javascript" src="../../jquery.js"></script>
        <script type="text/javascript" src="../../jquery.validity.js"></script>
        <script type="text/javascript">
            $(function() { 
                $("form").validity(function() { 
                    if ($("#maillist").attr("checked")) {
                        $("#email")
                            .require("We'll need #{field} if you want to be on the mailing list.")
                            .match("email");
                    }
                });
            });
        </script>
    </head>
    <body>
        <form action="conditional.htm" method="get">
            <input type="checkbox" id="maillist" name="maillist" />
            
            <label for="maillist">
                Yes, I'd like to recieve updates: 
            </label>
            
            <br />
            
            <label for="email">
                My email:
            </label>
            
            <input type="text" id="email" name="email" title="your address" />
            
            <br />
            
            <input type="submit" value="Submit" />
        </form>
    </body>
</html>
                

This is an example of using JavaScript control structures in the validity method.


Understanding Chains

You may have noticed that the validator functions can be called on the results of other validator methods in the manner of jQuery function chaining. For instance:

// Selector:       1st:      2nd:            3rd:         Chain ends:
$("#some_textbox").require().match("number").range(24, 64);
            

The basic mechanism involved with chains is that functions later in a chain will only do validation if the previous ones succeed.

In other words, in the above code snippet, if the input does not have a value (i.e. require() fails and raises an error) then validity is smart enough to not check the format when it gets to match("number"). It would be meaningless to complain about the format if there was no value to check.

In this fashion you can assign the validator methods in the order of most essential first, and then do the more specific rules later in the chain.

Requiring a value is more essentiall than restricting it to the format of a number. Restricting its format is more essential than checking its range.


Using a String Argument

If you only need to require some of the inputs, and you don't need to format-check them, you can simply pass a string into the validity method.

The string needs to be a jQuery selector expression that would select the elements you wish to validate.

In the following interactive example, we validate the page with the statement:

$("form").validity("input:text, select"); 
            

This is because the string argument would select all of the inputs we need.

[View Source]
<html>
    <head>
        <title>String Argument</title>
        <link type="text/css" rel="Stylesheet" href="../../jquery.validity.css" />
        <script type="text/javascript" src="../../jquery.js"></script>
        <script type="text/javascript" src="../../jquery.validity.js"></script>
        <script type="text/javascript">
            $(function() { 
                $("form").validity("input:text, select");
            });
        </script>
    </head>
    <body>
        <form method="get" action="stringargument.htm">
            <label for="PetName">Name of Pet:</label>
            <input type="text" id="PetName" name="PetName" title="name" />
            <br /><br />
            
            <label for="PetType">Type of Pet:</label>
            <select id="PetType" name="PetType" title="type">
                <option selected="selected"></option>
                <option>Dog</option>
                <option>Cat</option>
                <option>Bird</option>
                <option>Lizard</option>
                <option>Panda</option>
            </select>
            <br /><br />
            
            <label for="Petfoodbrand">Brand of Petfood:</label>
            <input type="text" id="Petfoodbrand" name="Petfoodbrand" title="brand" />
            <br /><br />
            
            <input type="submit" value="Submit" />
        </form>
    </body>
</html>
                

If we wished to make the petfood input optional, we could modify the string the same way we'd craft a jQuery selector to exclude this input. For example:

$("form").validity("input:text:not(#Petfoodbrand), select");
            

Using Validity with Ajax

If your page uses Ajax and cannot bind to a form in the way described above, or you otherwise wish not to use the validity method, you will need to manually call validity's start and end functions.

$.validity.start();

// And:

var result = $.validity.end();
            

These functions are really quite easy to use.

Essentially, the start function should be called before any validator methods. The end function should be called after all the validator methods have been called, and it returns an object representing the results of the validation.

The result object that is returned by the end function bears two properties: valid and errors.

For example, some code that would validate inputs without a form might look like this:

// This is the validation function:
function validateMyAjaxInputs() {

    // Start validation:
    $.validity.start();
    
    // Validator methods go here:
    
    // For instance:
    $("#my_textbox").require();
    
    // etc.
    
    // All of the validator methods have been called:
    // End the validation session:
    var result = $.validity.end();
    
    // Return whether it's okay to proceed with the Ajax:
    return result.valid;
}


// This is the function wired into the click event of some link or button:
function ajaxButtonClicked() {

    // First check whether the inputs are valid:
    if (validateMyAjaxInputs()) {
    
        // Do ajax:
        // ...
        
    }
}
            

Validators

Validity defines various methods onto jQuery objects for validation. We'll call these validator methods.


Common Validators

The common validator methods all deal specifically with individual inputs. Any of them can be called on jQuery objects of several inputs. Each input will be validated indivdiually.

In other words, we could use jQuery several times to select each input and call the 'require' validator method each time. Alternatively, and more elegantly, we could simply select all of the needed inputs and call 'require' once on that.

// For example:

// Wirting:
$('#input-1').require();
$('#input-2').require();
$('#input-3').require();
$('#input-4').require();
$('#input-5').require();

// Would be equivalent to:
$("#input-1, #input-2, #input-3, #input-4, #input-5").require();

// Or, if there are no other inputs than these five:
$("input").require();

// The power is in the selector.
            

Below are summarized the various common validator methods.


Require:

Signature:
jQuery("selector").require( ['message'] )
Arguments:
Overview:

This is the most basic validation method. It merely checks to ensure that inputs have values. If any do not have a value (i.e. value.length is zero) an error is raised for that input and the form should not be submitted.

Examples:
// Require all inputs, use the default error message.
$("input:text").require();
            
// A specific error message is attached to a specific input.
$("#ssn").require("Your Social Security Number is required to proceed.");
            

Match:

Signature:
jQuery("selector").match( 'patternName'|RegExp, ['message'] )
Arguments:
Overview:

Tests that the inputs conform to the specified format. This is achieved by passing in a Regexp to match the value against. validity also includes several common Regexps that you may use by merely passing in their name as a string.

The built-in Regexp names are:

integer
Will match only positive, whole numbers.
date
Will only match dates in the American mm/dd/yyyy format. To support other date formats refer to the Internationalization Section later on in this document.
email
Matches email addresses.
usd
Matches U.S. Dollar amounts.
url
Matches web-addresses.
number
Matches a number. It could be an integer or float, positive or negative or in scientific-notation.
zip
Matches an U.S. Postal Code (in both 5 and 9 digit forms).
phone
Matches an U.S. Domestic Phone number.
guid
Matches a globally unique identifier. Should be formatted such as
{3F2504E0-4F89-11D3-9A0C-0305E82C3301}
time12
Matches a time in 12-hour format.
time24
Matches a time in 24-hour format.
Examples:
// Make sure that all inputs under the 'date' class are 
// properly formatted. (Given they bear a value.) If any 
// fail, they will be tagged with a default error message 
// associated with the 'date' pattern.
$('input.date').match('date');
            
// Same as the previous example, but the dates are now required also.
$('input.date')
    .require()
    .match('date');
            
// Ensures that an input named 'employeeId' conforms to a 
// special, company-specific pattern, and specifies a 
// helpful message.
$('#employeeId').match(/^\d{2}[-]\d{4}$/, "Employee Ids must be in the form XX-XXXX.");
            
// Same as the previous example, but the message is tokenized:
$('#employeeId').match(/^\d{2}[-]\d{4}$/, "#{field} must be in the form XX-XXXX.");
            

Range:

Signature:
jQuery("selector").range( min, max, ['message'] )
Arguments:
Overview:

Will restrict the value to an inclusive numeric or date range. The min and max arguments should be either both numbers or both JavaScript date objects.

Since the range validator expects either numbers or dates you should use range after a match validator so that you may be sure that the values which are range-checked will be in a valid format.

Examples:
// Restrict valid values to an inclusive numeric range.
$("#percentage")
    .match(/^\d+\.?\d*%?/, "Must be formatted like a percent.")
    .range(0, 100);
            
// Restrict valid values to an inclusive temporal range.
$("#DayDuringClintonAdministration")
    .match('date')
    .range(new Date("01/20/1993"), new Date("01/20/2001"));
            

Greater Than/Greater Than or Equal To:

Signature:
jQuery("selector").greaterThan( min, ['message'] )
jQuery("selector").greaterThanOrEqualTo( min, ['message'] )
Arguments:
Overview:

Restricts the value to be larger than the specified minimum.

Since the greaterThan/greaterThanOrEqualTo validator expects either numbers or dates you should use it after a match validator so that you may be sure that the values which are checked will be in a valid format.

Examples:
// Validates a cost input, that it must be more than zero.
$("#cost")
    .match("usd")
    .greaterThan(0);
            
// Validates a velocity input, that it must be greater than or equal to zero.
$("#velocity")
    .match("number")
    .greaterThanOrEqualTo(0, "You cannot have negative velocity.");
            

Less Than/Less Than or Equal To:

Signature:
jQuery("selector").lessThan( max, ['message'] )
jQuery("selector").lessThanOrEqualTo( max, ['message'] )
Arguments:
Overview:

Restricts the value to be smaller than the specified minimum.

Since the lessThan/lessThanOrEqualTo validator expects either numbers or dates you should use it after a match validator so that you may be sure that the values which are checked will be in a valid format.

Examples:
// Validates an angle input, that it must be less than 180.
$("#angle")
    .match("number")
    .lessThan(180);
            
// Validates a hours input, that it must be less than or equal to 24.
$("#HoursPerDay")
    .match("integer")
    .lessThanOrEqualTo(24, "#{field} cannot be more than #{max}.");
    
// The resulting tokenized message could be "Hours Per Day cannot be more than 24."
            

Max Length/Min Length:

Signature:
jQuery("selector").maxLength( max, ['message'] )
jQuery("selector").minLength( min, ['message'] )
Arguments:
Overview:

Restricts the length of the value to the specified maximum or minimum. This validator is useful to restrict input values to the max-length allowed by a database schema.

Examples:
// Limit the length of a value to be less than 255:
$("textarea#description").maxLength(255);
            
// Specify a minimum length for the value:
$("#detailedExplaination")
    .minLength(1000, "You need to give more detail.");
            

Non HTML:

Signature:
jQuery("selector").nonHtml( ['message'] )
Arguments:
Overview:

Disallows the angle brackets necessary for XSS attacks.

Examples:
// Disallow HTML in the specified input:
$("#myBiography").nonHtml();
            

Aggregate Validators

Aggregate validators are able to do validation rules that involve more than one input. In a similar way to how aggregate functions in SQL take several records and gather them into one result, aggregate validators can take several HTML elements and determine whether they are valid with regard to eachother.

This feature of validity takes advantage of the jQuery selection engine to gather multiple results.


Equal:

Signature:
jQuery("selector").equal( [transform], ['message'] )
Arguments:
Overview:

Ensure that the values of all matched elements are equal to each other. This is an aggregate validator, meaning that it should be applied to groups of inputs.

A common use for the equal validator is in password-confirmation scenarios, where a form should not be submitted if a user fails to reenter his or her password correctly.

Examples:
// Write a jQuery selector that results in both the password and its confirmation,
// make sure that they conform to your password conditions with the match validator,
// then validate that result with 'equal'.
$("text[type='password']")
    .match(mySpecialPasswordRegex, myPasswordFormatMessage)
    .equal("Passwords do not match.");
            
// We can also extract the important part of a value, and test the equality only on that.
// For instance, we might want phone numbers to be equal disregarding whether they
// use '.' or '-' to separate groups, or have the area code in parentheses.
$("input.phone")
    .match("phone")
    .equal(
        function(val) { 
            return val.replace(/[-.()]/, '');
        },
        "All phone numbers must be the same."
    );
            

Distinct:

Signature:
jQuery("selector").distinct( [transform], ['message'] )
Arguments:
Overview:

Ensures that the values of all matched elements are distinct from each other. In other words, validate that no value is repeated among the matched elements.

If any of the matched elements do not have a value that element will not be tested. Consequently, the distinct validator will work with inputs that are or are not required.

Examples:
// Find all the inputs meant to hold Vehicle Identification Numbers.
// Since every VIN should be different, a repeat should be treated as invaid.
$("input.vin").distinct("A VIN Number was repeated.");
            
// We can also use a transform to normalize values.
// For instance, if we wish to ignore case 
// (i.e. if "abc" and "ABC" should be treated as a repeat)
// we can pass in a transform that makes all values upper-case.
// An example of this might be network interface hardware addresses.

// We'll allow the values to be in upper or lower case, 
// but treat those as the same value.
$("input.macAddress")
    .match(/([0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}/, "Must be a valid MAC address.")
    .distinct(
        function(val) { 
            return val.toUpperCase();
        },
        "A hardware address was repeated."
    );
            

Sum/Sum Max/Sum Min:

Signature:
jQuery("selector").sum( sum, ['message'] )
jQuery("selector").sumMax( max, ['message'] )
jQuery("selector").sumMin( min, ['message'] )
Arguments:
Overview:

Validate that the numeric sum of the value of all matched elements is equal to a given value or bounded by a specified max or min. If any value is not parseable as a number it will be ignored.

Examples:
// Find inputs representing the three interior angles of a triangle.
$("input.triangleAngle")
  .require()
  .match("number")
  .sum(180, "A triangle's angles should add up to 180 degrees.");
            
// Find inputs representing the how you intend to distribute 100,000 dollars among
// several people without having to distribute all of it.
$("input.distribution")
  .match("usd")
  .sumMax(100000, "You can't distribute more than you have on hand.");
            

Specialized Validation:

Validity supplies validator methods that cover the most common scenarios, but it also offers a tool to write your own custom validator with assert.

assert is at once the most complicated and most capable validator in the validity suite. It's use is thoroughly outlined below.


Assert:

Signature:
jQuery("selector").assert( expression|function, ['message'] )
Arguments:
Overview:

Assert allows you to validate inputs using your own customized logic, but still let validity display the error messages. If what you need is not provided among validity's built-in validator methods, you can write it yourself with assert. (In fact, any of the built in functions could be replicated with assert. It's that powerful.)

There are two general ways to use assert: you can pass in an expression argument (which evaluates into a boolean), or you can pass in a JavaScript function object. It is important to understand that assert will act like an aggregate validator when an expression is passed, but will act like a common (non-aggregate) validator when a function object is passed.

Examples:

To illustrate these techniques, we can write a validator to determine whether a set of inputs are all evens or all odds:

$(function() {
    $("form").validity(function() {
        // Store the information in local variables:
        // These are booleans:
        var allEvens = (
            parseFloat($("#box1").val()) % 2 == 0 &&
            parseFloat($("#box2").val()) % 2 == 0 &&
            parseFloat($("#box3").val()) % 2 == 0 &&
            parseFloat($("#box4").val()) % 2 == 0
        );
        var allOdds = (
            parseFloat($("#box1").val()) % 2 == 1 &&
            parseFloat($("#box2").val()) % 2 == 1 &&
            parseFloat($("#box3").val()) % 2 == 1 &&
            parseFloat($("#box4").val()) % 2 == 1
        );
        
        // Pass the OR of those two booleans as the expression argument into assert.
        // This will cause the inputs to be considered all valid or all invalid.
        $("#box1, #box2, #box3, #box4")
            .match("integer")
            .assert(
                (allEvens || allOdds), 
                "The inputs can either have all even numbers or all odd numbers. Not mixed."
            );
    });
});
            

As another example, we can pass a function object to perform common, non-aggregate validation. In the below example we can individually determine whether any of the selected inputs is a palindrome:

// First create the functions that will be used in validation.
        
// Helper to reverse a string:
function reverse(s){
    var  r = "";
    var  l = s.length;
    for (var i = l; i > 0; i--){
        r += s.charAt(i-1);
    }
    return r;
}

// Returns whether the value of the passed element is a palindrome:
// Notice that this function is meant to accept the DOM element, 
// not the value of the DOM element.
function isPalindrome(element){
    return element.value == reverse(element.value);
}
            
$(function() {
    $("form").validity(function() {
        // Instruct assert to use this function to test each input.
        // Notice that we're passing the function itself 
        // rather than the result of the function.
        // (i.e. "isPalindrome" not "isPalindrome()" )
        $(":text").assert(
            isPalindrome, 
            "#{field} must be a palindrome."
        );
    });
});
            

Tokenized Messages

Validity will attempt to generate helpful error messages based on how you validate what inputs. This feature is intended to minimize the number of error messages you'll be required to write yourself and to keep validation messages consistent.

Note: Validity will still grant you full control over the messages. You will not be forced to use this feature, although it can be used to simplify your code.


Understanding Tokenized Messages

The mechanism validity uses to generate these messages is a library of default message strings that contain tokens. For example, validity contains the following string as a default message for required field errors:

"#{field} is required."
            

The #{field} part at the beginning of the string is a token to be replaced with the title of the input for which the error is being created. In this way, a required field error being generated for an input titled "your name" will generate the message "Your name is required."

Similary, the tokenized message for range validators is:

"#{field} must be between #{min} and #{max}."
            

As you can see, there are tokens for the min and the max so that those values can be inserted into the error message. An example result message might be: "Age of car must be between 10 and 60."

Because every validator method allows you to pass in your own validation message to override the default, you may use tokens when you do this. For instance, if you use the match validator with your own regular expression to validate multiple inputs you might use a tokenized message in the following way:

$("input.ssn").match(
    /^\d{3}-\d{2}-\d{4}$/, 
    "#{field} needs to be in the format of a Social Security Number."
);
            

In this way you can have validity generate several messages for each input. The above statement might generate the error messages: "Your SSN needs to be in the format of a Social Security Number.", "Cosigner A SSN needs to be in the format of a Social Security Number.", and "Cosigner B SSN needs to be in the format of a Social Security Number."

Note: All default messages can be rewritten or modified to fit the parlance of your site. For information on how to do this refer to the Customizing Messages section later on in this document.


Best Practices

A significant part of how Validity generates error messages involves figuring out what the name of the input should be. Validity needs to guess the name of an input in order to insert that into the #{field} token of a tokenized message. It is important to understand how Validity makes this guess in order that you can help it to guess correctly.

  1. Validity will first look at the "title" attribute of an input. If an input has a title attribute Validity will assume that is its name. For example, if validity had to guess the name of the following input it will assume that it's "User Name" because that is the value of the title attribute.

    <input id="not_helpful" name="not_helpful" title="User Name" />
                        

    Using the title attribute in this way is the preferrable method. If you're able to set the title attribute of an input, you're advised to do so this way.

  2. Validity will next look at the "id" attribute of the element. If the id attribute appears to be in "Upper Camel Case" format (sometimes called Pascal Case) it will take that value and split it into words by inserting a space before each capital letter.

    For example, if Validity had to guess the name of the following input, it will assume that it's "User Name" because the value of the id attribute is in Upper Camel Case form and there is no "title" attribute.

    <input id="UserName" name="UserName" />
                        
  3. If the previous two checks have failed, Validity will check whether the id is in the form of lower-case words separated by underscores. If Validity finds this format, it will replace each underscore with a space and capitalize the first letter of each word.

    For example, Validity would assume the that name for the following input is "User Name".

    <input id="user_name" name="user_name" />
                        
  4. If Validity has failed the previous three tests, it will use a default field name which is built-in. This default name is:

    defaultFieldName: "This field"
                        

    Often, if Validity ends up using the default field name, the error messages will still be helpful and natural-looking because, with the label and modal output modes at least, error messages are positioned right next to the input to which they refer.

  5. Lastly, if you are not able to set the title attribute or do not have the ability to give your inputs meaningful ids and you don't wish the default field name to be used, you can always pass a specific non-tokenized string of your message into the validator call. Each and every validator will accept a string as its last argument to be used as the message.


Output Modes

Although Validity is able to validate inputs, its other role is to display errors appropriately and consistently. The logic that Validity uses to display errors is wrapped up into what's called an output mode. There are three output modes included with validity, each of which are summarized in the following sections.

You are also able to write your own output mode and get full control to how messages are displayed. For a full explanation of how to do this see the Writing a Custom Output Mode section later in this document.

You may instruct Validity which output mode you would like to use using the setup function. For example, to enable the "summary" output mode, the following code would be appropriate:

$.validity.setup({ outputMode:"summary" });
            

Label

Label is the default output mode in Validity. If you do not specify another output mode using the setup function, label will be what is used.

When this output mode creates an error message, it will create an HTML label element with the CSS class "error", the "for" attribute set to the id of the input it is being created for and the text of the error message. This label element is then positioned after the input it has been created for.

The advantage of this output mode is that it will place error messages very helpfully next to the offending inputs. Additionally, it does not require anything to be setup in advance (aside from the styles in the CSS file).

Although it's default, you would be able to enable the label output mode with the code:

$.validity.setup({ outputMode:"label" });
            

The Modal output mode acts similarly to Label - however, instead of inserting the error message into the HTML next to the input, it will position the message so that it hovers near the input.

In this way, using the Modal output mode will not mess up the layout of your site. Modal is very useful in web-designs involving tightly-knit tables or small areas.

You can enable the modal output mode with the code:

$.validity.setup({ outputMode:"modal" });
            

By default, modal error messages will disappear when they've been clicked. This behavior can be disabled with the following code:

$.validity.setup({ modalErrorsClickable:false });
            

Summary

The Summary output mode behaves quite differently from Label or Modal. Summary will gather all of the validation messages and compile them into a summary to be displayed when validation has concluded. Instead of placing the messages next to the inputs, it will highlight the input and the message will appear in the summary.

This is very useful in web pages with long forms to fill out, where it's important to keep the look clean and professional.

Also unlike Label and Modal, the Summary output mode requires a small amount of markup in order to operate. You will need to insert the following code wherever you want the summary of messages to appear:

<div class="validity-summary-container">
    Here's a summary of the validation failures:
    <ul></ul>
</div>
            

The text in this code snippet ("Here's a summary of the validation failures:") is a message that is meant to explain that it's part of a summary of validation errors. This message will not be shown if there are no errors. You are encouraged to edit this message as you see fit.

Essentially, the element with CSS class of validity-summary-container is shown or hidden depending whether there are any errors. The actual messages will be insterted into their individual <li/> elements into the <ul/> element inside of the container element.

You can enable the summary output mode with the code:

$.validity.setup({ outputMode:"summary" });
            

Customizing Validity Itself

Architectually, Validity is written along the programming principle of Separation of Concerns. In this way, Validity is able to allow developers to customize and replace components simply and safely. Here we summarize and guide through the different ways Validity can be modified.


Adapting the CSS

The simplest way to modify Validity is to adapt the CSS to the look of your site. As much as possible, Validity lets CSS decide how things look so that it can be safely modified without forcing you to hack JavaScript.

Validity comes with a boilerplate CSS file (jquery.validity.css). You may simply include this file on your site as a stylesheet reference, but are encouraged to copy and paste the styles from it into your own CSS file where you can edit them freely.

The CSS file contains three groups of styles. (One for each of the output modes. See Output Modes.) The groups you decide to copy over and modify should depend on which Output Modes you are using.


Label

The Label output mode uses a single style. The selector for this style is label.error, therefore it will be applied to all HTML label elements with the CSS class error.

The boilerplate CSS for this style is nothing special. It specifies some colors and a background image that grants the label an arrow-shaped corner on the left side. It also makes use of unstandardized properties that give the labels rounded corners in non-Internet-Explorer browsers. Below is an example:

The complete CSS style for the Label output mode is below:

label.error { 
    color:#fff; 
    margin-left:2px;     
    background-image:url('arrow.gif');
    background-position:left center;
    background-repeat:no-repeat;
    padding:2px;
    padding-left:18px;
    -moz-border-radius:4px;
    -webkit-border-radius: 4px;
}
            

To adapt the look of the label output mode, this style is all that must be changed.


Modal

The Modal output mode uses two styles by default. These styles are built around the validity-modal-msg CSS class. When Validity generates a Modal message, it will be placed under this class.

For the most part these styles determine the appearence of the messages (i.e. Background Color, Border, Padding, etc.), but it is important to note the position:absolute; statement. This property is necessary for the Modal errors to be positioned near the inputs. If you edit this style, do not change the position property.

The other style used by Modal is an hover pseudoclass that highlights the error messages to indicate that they might be clicked. If you disable the modalErrorsClickable setting (see Modal) you may wish to remove this style.

Below is an example:

This is a validation message.

The complete CSS styles for the Modal output mode are below:

.validity-modal-msg { 
    position:absolute; 
    z-index:2; 
    background-color:#999; 
    border:solid 1px #000; 
    padding:4px;
    cursor:pointer; 
}

.validity-modal-msg:hover { 
    background-color:#aaa; 
}
            

Summary

The Summary output mode uses three styles. The first two styles change the summary, whereas the third is for highlighting inputs that have errors.

The complete CSS styles for the Summary output mode are below:

.validity-summary-container { display:none; }
.validity-summary-output ul { }
.validity-erroneous { border:solid 2px #f56600 !important; }
            

When adapting these styles, the only property that should not be changed is the display:none; which is applied to elements with the CSS class validity-summary-container. This will keep the summary hidden by default so that it will not be shown when the page loads.

The UL element inside the container will house the errors. If you would like to modify the bullet-style or anything else to do with the list this second style will be where to do it.

This is the summary:
  • Here's a validation message.
  • Here's another validation message.

Customizing Messages

You can modify the default error messages that are built into Validity. If you dislike the wording of any of these default messages you may override them easily. Executing the following code will overrite all of the messages.

$.extend($.validity.messages, {
    require:"#{field} is required.",

    // Format validators:
    match:"#{field} is in an invalid format.",
    integer:"#{field} must be a positive, whole number.",
    date:"#{field} must be formatted as a date.",
    email:"#{field} must be formatted as an email.",
    usd:"#{field} must be formatted as a US Dollar amount.",
    url:"#{field} must be formatted as a URL.",
    number:"#{field} must be formatted as a number.",
    zip:"#{field} must be formatted as a zipcode ##### or #####-####.",
    phone:"#{field} must be formatted as a phone number ###-###-####.",
    guid:"#{field} must be formatted as a guid like {3F2504E0-4F89-11D3-9A0C-0305E82C3301}.",
    time24:"#{field} must be formatted as a 24 hour time: 23:00.",
    time12:"#{field} must be formatted as a 12 hour time: 12:00 AM/PM",

    // Value range messages:
    lessThan:"#{field} must be less than #{max}.",
    lessThanOrEqualTo:"#{field} must be less than or equal to #{max}.",
    greaterThan:"#{field} must be greater than #{min}.",
    greaterThanOrEqualTo:"#{field} must be greater than or equal to #{min}.",
    range:"#{field} must be between #{min} and #{max}.",

    // Value length messages:
    tooLong:"#{field} cannot be longer than #{max} characters.",
    tooShort:"#{field} cannot be shorter than #{min} characters.}",

    // Aggregate validator messages:
    equal:"Values don't match.",
    distinct:"A value was repeated.",
    sum:"Values don't add to #{sum}.",
    sumMax:"The sum of the values must be less than #{max}.",
    sumMin:"The sum of the values must be greater than #{min}.",

    nonHtml:"#{field} cannot contain Html characters.",

    generic:"Invalid."
});
            

With the above code snippet, you may edit any of the strings and Validity will subsequently use that for the default message. As an alternative syntax you may simply edit the strings in the following way:

$.validity.messages.match = "The format of #{field} is totally wrong.";
            

Please note that the #{field} token is never used in aggregate validator messages because they do not deal with any particular field. (See Tokenized Messages.)


Customizing/Extending Match Validator Support

You can add more format checkers to the Validity match validator with the following syntax.

// Adds match validator support to format-check against list of email addresses 
// separated by semicolons.
// Lovingly borrowed from http://regexlib.com/REDetails.aspx?regexp_id=1007

// Add the pattern:
$.validity.patterns.emailList = /^(([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+([;.](([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+)*$/;

// Add the message under the same name:
$.validity.messages.emailList = "#{field} must be formatted as a series of email-addresses separated by semicolons.";
            

As you can see, we add the pattern under the name emailList and also add a message under the same name. Now that that's been executed, we can pass that name into the match validator. For example:

// You can simply use the name of your new format and pass it in as a string:
$("#ListOfEmailAddresses")
    .require()
    .match("emailList");
            

Note that, when adding a format to the match validator, adding the message is optional, but recommended.

Using the same syntax, you are also able to override the Regular Expressions used by the built-in formats.


Language Packages/Internationalization

Because of the many ways that Validity can be customized, writing an Internationalization package is relatively simple. As an example the following code will install a Russian-language package which will change the validation messages into Russian and change some of the match-validator expressions:

$.extend($.validity.messages, {
    require:"#{field} обязательное поле.",
    match:"#{field} неправильный формат.",
    integer:"#{field} должно быть положительным числом.",
    date:"#{field} должно быть отформатирован как дата. (число.месяц.Год, 04.05.2006)",
    email:"#{field} должно быть отформатированы как адреса электронной почты.",
    usd:"#{field} должно быть отформатированы как деньги США.",
    url:"#{field} должно быть отформатированы как URL.",
    number:"#{field} должно быть отформатирован в виде числа.",
    zip:"#{field} должно быть отформатированы как почтовый индекс. (###)",
    phone:"#{field} должно быть отформатированы как телефонный номер.",
    guid:"#{field} должно быть отформатированы как GUID (как {3F2504E0-4F89-11D3-9A0C-0305E82C3301}).",
    time24:"#{field} должно быть отформатированы 24-часовой.",
    time12:"#{field} должно быть отформатированы 12-часовой. (12:00 AM/PM)",

    // Value range messages:
    lessThan:"#{field} должно быть меньше #{max}.",
    lessThanOrEqualTo:"#{field} должно быть меньше или равным #{max}.",
    greaterThan:"#{field} должно быть больше #{min}.",
    greaterThanOrEqualTo:"#{field} должно быть больше или равно #{min}.",
    range:"#{field} должно быть между #{min} и #{max}.",

    // Value length messages:
    tooLong:"#{field} может быть не более #{max} букв.",
    tooShort:"#{field} может быть не меньше #{min} букв.}",

    // Aggregate validator messages:
    equal:"Значения не равны.",
    distinct:"Было повторено значения.",
    sum:"Показатели не добавить до #{sum}.",
    sumMax:"Сумма значений должно быть меньше #{max}.",
    sumMin:"Сумма значений должно быть больше #{min}.",

    nonHtml:"#{field} не может содержать символы HTML.",

    generic:"Неверно."
});

$.validity.setup({ defaultFieldName:"поле" });

$.extend($.validity.patterns, {
    // Based off of http://en.wikipedia.org/wiki/Calendar_date
    date:/^([012]\d|30|31)\.([01]\d)\.\d{1,4}$/, 
    
    // Russian postal codes, based off of http://en.wikipedia.org/wiki/List_of_postal_codes_in_Russia
    zip: /^\d{3}$/,
    
    // Russian phone number pattern from http://regexlib.com/REDetails.aspx?regexp_id=1463
    phone: /((8|\+7)-?)?\(?\d{3,5}\)?-?\d{1}-?\d{1}-?\d{1}-?\d{1}-?\d{1}((-?\d{1})?-?\d{1})?/
});
            

Writing a Custom Output Mode

A major goal of Validity is to allow complete control over how validation messages appear so that they can look like they belong in your site. If adapting the CSS of any of the existing output modes isn't sufficient to make it look right you can write your own output mode from the ground up.

This may sound difficult, but thanks to Validity's philosophy of Separation of Interests it's really rather trivial. It involves two steps: first you install your custom output mode, then you enable it.

Here's a template for creating your own custom output mode. The code is actually very sparce, but may look complex on account of all the comments:

(function(){

    // The output mode will be named whatever you assign it to.
    // In this example, since we're assigning it to 'myOutputMode'
    // it will be called 'myOutputMode'.
    $.validity.outputs.myOutputMode = {
    
        // The start function will be called when validation starts.
        // This allows you to prepare the page for validation, for instance
        // you might remove any validation messages that are already on the page.
        start:function(){ 
        
        },
        
        // The end function is called when validation has concluded.
        // This allows you to flush any buffers or do anything you need to
        // after all of the validators have been called.
        // results will be the results object.
        // results.valid is a boolean representing whether the form is valid.
        // results.errors is an integer of how many errors there are.
        end:function(results) { 
        
        },
        
        // The raise function is called to raise an error for a specific input.
        // The first argument is a jQuery object of the input to raise the error message for.
        // The second argument is the string of the error message.
        raise:function($obj, msg){
        
        },
        
        // The raiseAggregate function is similar to the raise function, except that
        // the $obj argument will be a jQuery object of several inputs, 
        // all of which are invalid aggregately.
        raiseAggregate:function($obj, msg){ 
        
        },
    }
})();

// Now enable the output mode we just installed.
$.validity.setup({ outputMode:'myOutputMode' });
            

As an example, here is an output mode that will raise a JavaScript alert box, and then animate the border of the bad input:

// First install the new output mode:
(function(){
    
    // We'll decide to install our custom output mode under the name 'custom':
    $.validity.outputs.custom = {
        
        // In this case, the start function will just reset the inputs:
        start:function(){ 
        
            $("input:text")
                .css({border:'1px solid green'})
                .removeClass('fail');
                
        },
        
        end:function(results) { 
        
            // If not valid and scrollTo is enabled, scroll the page to the first error.
            if (!results.valid && $.validity.settings.scrollTo) {
                location.hash = $(".fail:eq(0)").attr('id')
            }
            
        },
        
        // Our raise function will display the error and animate the text-box:
        raise:function($obj, msg){
            
            // Make the JavaScript alert box with the message:
            alert(msg);
            
            // Animate the border of the text box:
            $obj
                .animate({ borderWidth: "10px" }, 1000)
                .css({borderColor:'red'})
                .addClass('fail');
                
        },
        
        // Our aggregate raise will just raise the error on the last input:
        raiseAggregate:function($obj, msg){ 
        
            this.raise($($obj.get($obj.length - 1)), msg); 
            
        }
    }
})();

// Now enable the output mode we just installed.
$.validity.setup({ outputMode:'custom' });

// Our custom output mode is installed and will be used whenever Validity is run.
            

Below is an example of this output mode in action. Try submitting it without entering anything in the text-box.

[View Source]
<html>
  <head>
    <title>Custom Output</title>
    <script type="text/javascript" src="../../jquery.js"></script>
    <script type="text/javascript" src="../../jquery.validity.js"></script>
    <script type="text/javascript">
        (function(){
            $.validity.outputs.custom = {
                start:function(){ 
                    $("input:text")
                        .css({border:'1px solid green'})
                        .removeClass('fail');
                },
                
                end:function(results) {
                    // If not valid and scrollTo is enabled, scroll the page to the first error.
                    if (!results.valid && $.validity.settings.scrollTo) {
                        location.hash = $(".fail:eq(0)").attr('id')
                    }
                },
                
                raise:function($obj, msg){
                    alert(msg);
                    $obj
                        .animate({ borderWidth: "10px" }, 1000)
                        .css({borderColor:'red'})
                        .addClass('fail');
                },
                
                // Just raise the error on the last input.
                raiseAggregate:function($obj, msg){ 
                    this.raise($($obj.get($obj.length - 1)), msg); 
                }
            }
            
            $.validity.setup({ outputMode:'custom' });
        })();
          
        // Instruct validity to validate the page by requiring 
        // the input matched by a jQuery selector.
        $(function() { $("form").validity("#text"); });
    </script>
  </head>
  <body>
    <form action="customoutput.htm" method="post">
      This field is required:
      <input type="text" id="text" name="text" style="border:solid 1px green" />
      <input type="submit" />
    </form>
  </body>
</html>

                

Using the template above, you can easily make your own output mode and package it nicely in its own, reuseable, easily shared JavaScript file.


Miscellaneous


The Setup Function

Validity supplies a setup function to let you modify global Validity settings. The syntax for this function, and all of the settings you have access to are below:

$.validity.setup({
    // You may change the output mode with this property.
    outputMode: "label",

    // The this property is set to true, validity will scroll the browser viewport
    // so that the first error is visible when validation fails.
    scrollTo: false,

    // If this setting is true, modal errors will disappear when they are clicked on.
    modalErrorsClickable: true,

    // If a field name cannot be otherwise inferred, this will be used.
    defaultFieldName: "This field"
});
            

You may edit any or all of these settings at once.


[Scroll back to the top]