jquery.validity guide & documentation

33
jQuery.validity Guide & Documentation Table of Contents: Introduction Setup Assigning Validation The Validity Method Using a Function Argument Basics Understanding Chains Using a String Argument Using Validity With Ajax Validators Common Validators Require Match Range Greater Than/Greater Than or Equal To Less Than/Less Than or Equal To Max Length/Min Length Non HTML Aggregate Validators Equal Distinct Sum/Sum Max/Sum Min Specialized Validation Assert Tokenized Messages Understanding [Scroll back to the top ] jQuery.validity Guide & Documentation http://validity.thatscaptaintoyou.com/Demos/index.htm 1 of 33 22/12/2010 08:06 ص

Upload: vegatr0n

Post on 20-Feb-2015

52 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: jQuery.validity Guide & Documentation

jQuery.validity Guide & Documentation

Table of Contents:IntroductionSetupAssigning Validation

The Validity MethodUsing a Function Argument

BasicsUnderstanding Chains

Using a String ArgumentUsing Validity With Ajax

ValidatorsCommon Validators

RequireMatchRangeGreater Than/Greater Than or Equal ToLess Than/Less Than or Equal ToMax Length/Min LengthNon HTML

Aggregate ValidatorsEqualDistinctSum/Sum Max/Sum Min

Specialized ValidationAssert

Tokenized MessagesUnderstanding [Scroll back to the top]

jQuery.validity Guide & Documentation http://validity.thatscaptaintoyou.com/Demos/index.htm

1 of 33 ص 08:06 22/12/2010

Page 2: jQuery.validity Guide & Documentation

Best PracticesOutput Modes

LabelModalSummary

Customizing Validity ItselfAdapting the CSS

LabelModalSummary

Customizing MessagesCustomizing/Extending Match Validator SupportLanguage Packages/InternationalizationWriting a Custom Output Mode

MiscellaneousThe Setup Function

Introduction:

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

Easy Setup: Validity employs the principle of Convention Over Configuration to aid in keepingcode manageable and semantic. Very little work is required to enable Validity for a page.

1.

Unobtrusive JavaScript: Using Validity will have little to no effect on the semantics of yourmarkup. Additionally, Validity will degrade gracefully and leave no residuals in browserenvironments where JavaScript is disabled or unsupported.

2.

Customizable Appearence: Validity is an effort to deliver a solid core-library of validation toolsthat can be used in any web-design. Therefore, in order to be truly versatile, validation logic isseparated from the way it displays errors. With Validity, you, the developer, have full control oferror message handling and adapting it to the design of your page.

3.

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

Setup:[Scroll back to the top]

jQuery.validity Guide & Documentation http://validity.thatscaptaintoyou.com/Demos/index.htm

2 of 33 ص 08:06 22/12/2010

Page 3: jQuery.validity Guide & Documentation

In order to use Validity on a page, you will need to import the jQuery JavaScript library as well asjQuery.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 thefollowing 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 logicusing the validity method. Normally, this the validity method is called on jQuery objects of HTMLforms and accepts a function as argument. As you can see, in the code above, a jQuery selector findsthe 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 theform of a number between 4 and 12. The second field will need to be a date and that date will have tobe at some point in the past.

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

[Scroll back to the top]

jQuery.validity Guide & Documentation http://validity.thatscaptaintoyou.com/Demos/index.htm

3 of 33 ص 08:06 22/12/2010

Page 4: jQuery.validity Guide & Documentation

$("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 alltogether, the interactive example below is produced.

[View Source]

Note: As of versiom 1.0.2+ you'll also need to put the arrow.gif image in the same directory as thestylesheet. (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.

In the Setup example the validity method is used with a function argument. For example:

// The validity method is being called on the form.$("form").validity(function() {

// This function is being passed into the validity method. // Validation logic can go here. });

More on this technique below under Using a Function Argument.

The validity method can also be called with a string argument. For example:[Scroll back to the top]

jQuery.validity Guide & Documentation http://validity.thatscaptaintoyou.com/Demos/index.htm

4 of 33 ص 08:06 22/12/2010

Page 5: jQuery.validity Guide & Documentation

// The validity method is being called on the form with a string argument.$("form").validity("input:text, select");

More on this technique below under Using a String Argument.

Furthermore, validity can be used without the validity method, for instance, when validatingAjax.

More on this technique below under Using Validity with Ajax.

The Validity Method

The validity method is defined on all jQuery objects, however it will only effect form elements. Youmay use it to select one or more forms and register the validation for each. There are two argumenttypes 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 youwill call the validator methods.

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

For Advanced Users: the other advantage to function arguments is your ability to use JavaScript control structures (such asif...else blocks, iterators, etc.). In other words, the function passed into the validity method is executed just like any otherJavaScript function. If your validation rules are conditional, nonlinear or otherwise complicated you can write whatever logicyou 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() {[Scroll back to the top]

jQuery.validity Guide & Documentation http://validity.thatscaptaintoyou.com/Demos/index.htm

5 of 33 ص 08:06 22/12/2010

Page 6: jQuery.validity Guide & Documentation

// 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 singlestatement. For instance, if a page has several inputs that need to represent percentages, and that allneed 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 followinginteractive example, an if...then structure is used to require an email input only if the checkbox ischecked.

[View Source]

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 validatormethods in the manner of jQuery function chaining. For instance:

[Scroll back to the top]

jQuery.validity Guide & Documentation http://validity.thatscaptaintoyou.com/Demos/index.htm

6 of 33 ص 08:06 22/12/2010

Page 7: jQuery.validity Guide & Documentation

// 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 ifthe previous ones succeed.

In other words, in the above code snippet, if the input does not have a value (i.e. require() fails andraises 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 dothe 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 thanchecking 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 cansimply pass a string into the validity method.

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

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]

[Scroll back to the top]

jQuery.validity Guide & Documentation http://validity.thatscaptaintoyou.com/Demos/index.htm

7 of 33 ص 08:06 22/12/2010

Page 8: jQuery.validity Guide & Documentation

If we wished to make the petfood input optional, we could modify the string the same way we'd crafta 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 wishnot 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 shouldbe called after all the validator methods have been called, and it returns an object representing theresults of the validation.

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

valid is a boolean representing whether no errors occurred between the times that start andend were called. If there were no errors, valid will be 'true'.errors is an integer representing how many errors occurred. If valid is 'true' then errors will be'0'.

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(); [Scroll back to the top]

jQuery.validity Guide & Documentation http://validity.thatscaptaintoyou.com/Demos/index.htm

8 of 33 ص 08:06 22/12/2010

Page 9: jQuery.validity Guide & Documentation

// 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 calledon 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' validatormethod each time. Alternatively, and more elegantly, we could simply select all of the needed inputsand 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(); [Scroll back to the top]

jQuery.validity Guide & Documentation http://validity.thatscaptaintoyou.com/Demos/index.htm

9 of 33 ص 08:06 22/12/2010

Page 10: jQuery.validity Guide & Documentation

// The power is in the selector.

Below are summarized the various common validator methods.

Require:

Signature:

jQuery("selector").require( ['message'] )

Arguments:

message: An optional message to display if an element fails.

Overview:

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

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:

patternName: A named pattern to match against. A list of the named formats that are built intovalidity can be found below. [Scroll back to the top]

jQuery.validity Guide & Documentation http://validity.thatscaptaintoyou.com/Demos/index.htm

10 of 33 ص 08:06 22/12/2010

Page 11: jQuery.validity Guide & Documentation

RegExp: Instead of a named pattern, you may enter a RegExp object to use for testing the value.message: An optional message to display if an element fails.

Overview:

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

The built-in Regexp names are:

integerWill match only positive, whole numbers.

dateWill only match dates in the American mm/dd/yyyy format. To support other date formats referto the Internationalization Section later on in this document.

emailMatches email addresses.

usdMatches U.S. Dollar amounts.

urlMatches web-addresses.

numberMatches a number. It could be an integer or float, positive or negative or in scientific-notation.

zipMatches an U.S. Postal Code (in both 5 and 9 digit forms).

phoneMatches an U.S. Domestic Phone number.

guidMatches a globally unique identifier. Should be formatted such as{3F2504E0-4F89-11D3-9A0C-0305E82C3301}

time12Matches a time in 12-hour format.

time24Matches 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') [Scroll back to the top]

jQuery.validity Guide & Documentation http://validity.thatscaptaintoyou.com/Demos/index.htm

11 of 33 ص 08:06 22/12/2010

Page 12: jQuery.validity Guide & Documentation

.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:

min: The inclusive lower-bound for valid values.max: The inclusive upper-bound for valid values.message: An optional message to display if an element fails.

Overview:

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

Since the range validator expects either numbers or dates you should use range after a matchvalidator 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"));

[Scroll back to the top]

jQuery.validity Guide & Documentation http://validity.thatscaptaintoyou.com/Demos/index.htm

12 of 33 ص 08:06 22/12/2010

Page 13: jQuery.validity Guide & Documentation

Greater Than/Greater Than or Equal To:

Signature:

jQuery("selector").greaterThan( min, ['message'] )

jQuery("selector").greaterThanOrEqualTo( min, ['message'] )

Arguments:

min: The lower-bound for valid values.message: An optional message to display if an element fails.

Overview:

Restricts the value to be larger than the specified minimum.

Since the greaterThan/greaterThanOrEqualTo validator expects either numbers or dates you shoulduse it after a match validator so that you may be sure that the values which are checked will be in avalid 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:

max: The upper-bound for valid values.message: An optional message to display if an element fails. [Scroll back to the top]

jQuery.validity Guide & Documentation http://validity.thatscaptaintoyou.com/Demos/index.htm

13 of 33 ص 08:06 22/12/2010

Page 14: jQuery.validity Guide & Documentation

Overview:

Restricts the value to be smaller than the specified minimum.

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

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:

max: The upper-bound for the length of valid values.min: The lower-bound for the length of valid values.message: An optional message to display if an element fails.

Overview:

Restricts the length of the value to the specified maximum or minimum. This validator is useful torestrict 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);

[Scroll back to the top]

jQuery.validity Guide & Documentation http://validity.thatscaptaintoyou.com/Demos/index.htm

14 of 33 ص 08:06 22/12/2010

Page 15: jQuery.validity Guide & Documentation

// Specify a minimum length for the value:$("#detailedExplaination") .minLength(1000, "You need to give more detail.");

Non HTML:

Signature:

jQuery("selector").nonHtml( ['message'] )

Arguments:

message: An optional message to display if an element fails.

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 wayto how aggregate functions in SQL take several records and gather them into one result, aggregatevalidators can take several HTML elements and determine whether they are valid with regard toeachother.

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

Equal:[Scroll back to the top]

jQuery.validity Guide & Documentation http://validity.thatscaptaintoyou.com/Demos/index.htm

15 of 33 ص 08:06 22/12/2010

Page 16: jQuery.validity Guide & Documentation

Signature:

jQuery("selector").equal( [transform], ['message'] )

Arguments:

transform: Optional transform function to apply to each value before testing.message: An optional message to display if an element fails.

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 notbe 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:

transform: Optional transform function to apply to each value before testing.message: An optional message to display if an element fails.

[Scroll back to the top]

jQuery.validity Guide & Documentation http://validity.thatscaptaintoyou.com/Demos/index.htm

16 of 33 ص 08:06 22/12/2010

Page 17: jQuery.validity Guide & Documentation

Overview:

Ensures that the values of all matched elements are distinct from each other. In other words, validatethat 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, thedistinct 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:

sum: The value that the sum of matched elements should be equal to.max: The inclusive upper-bound for the sum of matched elementsmin: The inclusive lower-bound for the sum of matched elementsmessage: An optional message to display if an element fails.

[Scroll back to the top]

jQuery.validity Guide & Documentation http://validity.thatscaptaintoyou.com/Demos/index.htm

17 of 33 ص 08:06 22/12/2010

Page 18: jQuery.validity Guide & Documentation

Overview:

Validate that the numeric sum of the value of all matched elements is equal to a given value orbounded 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 towrite your own custom validator with assert.

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

Assert:

Signature:

jQuery("selector").assert( expression|function, ['message'] )

Arguments:

expression: Any expression that will result in a boolean. When expression evaluates to true thevalidator succeeds. Keep in mind, when passing an expression rather than a function, assert willact like an aggregate validator. That is to say, the truth or falsehood of expression will determinethe validity of ALL matched elements.function: A javascript function object which will accept a DOM Element and return true or falserepresenting whether that DOM element was valid. Keep in mind that when passing a function[Scroll back to the top]

jQuery.validity Guide & Documentation http://validity.thatscaptaintoyou.com/Demos/index.htm

18 of 33 ص 08:06 22/12/2010

Page 19: jQuery.validity Guide & Documentation

rather than an expression assert will act like a common (non-aggregate) validator. That is to saythat the function will be applied to each and every matched element and their validity isdetermined individually.message: An optional message to display if an element fails. While this argument is optional, it isstrongly encouraged for use with the assert validator.

Overview:

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

There are two general ways to use assert: you can pass in an expression argument (which evaluatesinto a boolean), or you can pass in a JavaScript function object. It is important to understand thatassert 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 allevens 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. Inthe 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. [Scroll back to the top]

jQuery.validity Guide & Documentation http://validity.thatscaptaintoyou.com/Demos/index.htm

19 of 33 ص 08:06 22/12/2010

Page 20: jQuery.validity Guide & Documentation

// 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 MessagesValidity will attempt to generate helpful error messages based on how you validate what inputs. Thisfeature is intended to minimize the number of error messages you'll be required to write yourself andto keep validation messages consistent.

Note: Validity will still grant you full control over the messages. You will not be forced to use thisfeature, 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 thatcontain tokens. For example, validity contains the following string as a default message for requiredfield errors: [Scroll back to the top]

jQuery.validity Guide & Documentation http://validity.thatscaptaintoyou.com/Demos/index.htm

20 of 33 ص 08:06 22/12/2010

Page 21: jQuery.validity Guide & Documentation

"#{field} is required."

The #{field} part at the beginning of the string is a token to be replaced with the title of the input forwhich 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 theerror 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 thedefault, you may use tokens when you do this. For instance, if you use the match validator with yourown regular expression to validate multiple inputs you might use a tokenized message in thefollowing 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 statementmight generate the error messages: "Your SSN needs to be in the format of a Social SecurityNumber.", "Cosigner A SSN needs to be in the format of a Social Security Number.", and "Cosigner BSSN 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. Forinformation 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 theinput 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 orderthat you can help it to guess correctly.

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

1.

[Scroll back to the top]

jQuery.validity Guide & Documentation http://validity.thatscaptaintoyou.com/Demos/index.htm

21 of 33 ص 08:06 22/12/2010

Page 22: jQuery.validity Guide & Documentation

<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 titleattribute of an input, you're advised to do so this way.

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 intowords 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" />

2.

If the previous two checks have failed, Validity will check whether the id is in the form oflower-case words separated by underscores. If Validity finds this format, it will replace eachunderscore 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" />

3.

If Validity has failed the previous three tests, it will use a default field name which is built-in. Thisdefault name is:

defaultFieldName: "This field"

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

4.

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

5.

Output Modes[Scroll back to the top]

jQuery.validity Guide & Documentation http://validity.thatscaptaintoyou.com/Demos/index.htm

22 of 33 ص 08:06 22/12/2010

Page 23: jQuery.validity Guide & Documentation

Although Validity is able to validate inputs, its other role is to display errors appropriately andconsistently. The logic that Validity uses to display errors is wrapped up into what's called an outputmode. There are three output modes included with validity, each of which are summarized in thefollowing 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 thisdocument.

You may instruct Validity which output mode you would like to use using the setup function. Forexample, 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 thesetup function, label will be what is used.

When this output mode creates an error message, it will create an HTML label element with the CSSclass "error", the "for" attribute set to the id of the input it is being created for and the text of the errormessage. 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 theoffending inputs. Additionally, it does not require anything to be setup in advance (aside from thestyles 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" });

Modal

The Modal output mode acts similarly to Label - however, instead of inserting the error message intothe 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[Scroll back to the top]

jQuery.validity Guide & Documentation http://validity.thatscaptaintoyou.com/Demos/index.htm

23 of 33 ص 08:06 22/12/2010

Page 24: jQuery.validity Guide & Documentation

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 bedisabled with the following code:

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

Summary

The Summary output mode behaves quite differently from Label or Modal. Summary will gather all ofthe validation messages and compile them into a summary to be displayed when validation hasconcluded. Instead of placing the messages next to the inputs, it will highlight the input and themessage 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 cleanand professional.

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

<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 ismeant to explain that it's part of a summary of validation errors. This message will not be shown ifthere 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 dependingwhether there are any errors. The actual messages will be insterted into their individual <li/> elementsinto the <ul/> element inside of the container element.

You can enable the summary output mode with the code:

$.validity.setup({ outputMode:"summary" }); [Scroll back to the top]

jQuery.validity Guide & Documentation http://validity.thatscaptaintoyou.com/Demos/index.htm

24 of 33 ص 08:06 22/12/2010

Page 25: jQuery.validity Guide & Documentation

Customizing Validity Itself

Architectually, Validity is written along the programming principle of Separation of Concerns. In thisway, Validity is able to allow developers to customize and replace components simply and safely. Herewe 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 hackJavaScript.

Validity comes with a boilerplate CSS file (jquery.validity.css). You may simply include this file on yoursite as a stylesheet reference, but are encouraged to copy and paste the styles from it into your ownCSS 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 areusing.

Label

The Label output mode uses a single style. The selector for this style is label.error, therefore it will beapplied 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 imagethat grants the label an arrow-shaped corner on the left side. It also makes use of unstandardizedproperties that give the labels rounded corners in non-Internet-Explorer browsers. Below is anexample:

This is a validation message.

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; [Scroll back to the top]

jQuery.validity Guide & Documentation http://validity.thatscaptaintoyou.com/Demos/index.htm

25 of 33 ص 08:06 22/12/2010

Page 26: jQuery.validity Guide & Documentation

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 isnecessary for the Modal errors to be positioned near the inputs. If you edit this style, do not changethe position property.

The other style used by Modal is an hover pseudoclass that highlights the error messages to indicatethat they might be clicked. If you disable the modalErrorsClickable setting (see Modal) you may wishto 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; }

[Scroll back to the top]

jQuery.validity Guide & Documentation http://validity.thatscaptaintoyou.com/Demos/index.htm

26 of 33 ص 08:06 22/12/2010

Page 27: jQuery.validity Guide & Documentation

Summary

The Summary output mode uses three styles. The first two styles change the summary, whereas thethird 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; whichis applied to elements with the CSS class validity-summary-container. This will keep the summaryhidden 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-styleor anything else to do with the list this second style will be where to do it.

This is a bad input.

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 anyof these default messages you may override them easily. Executing the following code will overrite allof 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}.", [Scroll back to the top]

jQuery.validity Guide & Documentation http://validity.thatscaptaintoyou.com/Demos/index.htm

27 of 33 ص 08:06 22/12/2010

Page 28: jQuery.validity Guide & Documentation

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 thatfor 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 notdeal 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

// 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 samename. 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") [Scroll back to the top]

jQuery.validity Guide & Documentation http://validity.thatscaptaintoyou.com/Demos/index.htm

28 of 33 ص 08:06 22/12/2010

Page 29: jQuery.validity Guide & Documentation

.require() .match("emailList");

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

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

Language Packages/Internationalization

Because of the many ways that Validity can be customized, writing an Internationalization package isrelatively simple. As an example the following code will install a Russian-language package which willchange 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:"Неверно."});

[Scroll back to the top]

jQuery.validity Guide & Documentation http://validity.thatscaptaintoyou.com/Demos/index.htm

29 of 33 ص 08:06 22/12/2010

Page 30: jQuery.validity Guide & Documentation

$.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 theycan look like they belong in your site. If adapting the CSS of any of the existing output modes isn'tsufficient 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 rathertrivial. 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, butmay 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){ [Scroll back to the top]

jQuery.validity Guide & Documentation http://validity.thatscaptaintoyou.com/Demos/index.htm

30 of 33 ص 08:06 22/12/2010

Page 31: jQuery.validity Guide & Documentation

}, // 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 theborder 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); }

[Scroll back to the top]

jQuery.validity Guide & Documentation http://validity.thatscaptaintoyou.com/Demos/index.htm

31 of 33 ص 08:06 22/12/2010

Page 32: jQuery.validity Guide & Documentation

}})();

// 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 thetext-box.

[View Source]

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

Miscellaneous

The Setup Function

Validity supplies a setup function to let you modify global Validity settings. The syntax for thisfunction, 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, [Scroll back to the top]

jQuery.validity Guide & Documentation http://validity.thatscaptaintoyou.com/Demos/index.htm

32 of 33 ص 08:06 22/12/2010

Page 33: jQuery.validity Guide & Documentation

// 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]

jQuery.validity Guide & Documentation http://validity.thatscaptaintoyou.com/Demos/index.htm

33 of 33 ص 08:06 22/12/2010