- Overview
- Documents
jQuery.validity is a plugin designed to aid in the configuration of clientside form-validation. Validity was concieved with three goals:
- 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.
- 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.
- 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.
buyutucu pompa Spanish Fly
Source: validity.thatscaptaintoyou.com
1. INCLUDE CSS AND JS FILES
<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>
2. HTML
<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>
3. JAVASCRIPT
$("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): });
4. 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:
- 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 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:
- patternName: A named pattern to match against. A list of the named formats that are built into validity can be found below.
- 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 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 theInternationalization Section later on in this document.
- 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:
- 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 be either bothnumbers 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:
- 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 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:
- max: The upper-bound for valid values.
- message: An optional message to display if an element fails.
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:
- 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 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:
- 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 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:
- 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 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:
- transform: Optional transform function to apply to each value before testing.
- message: An optional message to display if an element fails.
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 distinctvalidator 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 elements
- min: The inclusive lower-bound for the sum of matched elements
- message: An optional message to display if an element fails.
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:
- expression: Any expression that will result in a boolean. When expression evaluates to true the validator succeeds. Keep in mind, when passing an expression rather than a function, assert will act like an aggregate validator. That is to say, the truth or falsehood of expression will determine the validity of ALL matched elements.
- function: A javascript function object which will accept a DOM Element and return true or false representing whether that DOM element was valid. Keep in mind that when passing a function rather than an expression assert will act like a common (non-aggregate) validator. That is to say that the function will be applied to each and every matched element and their validity is determined individually.
- message: An optional message to display if an element fails. While this argument is optional, it is strongly encouraged for use with the assert validator.
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." ); }); });
More information at: http://validity.thatscaptaintoyou.com/Demos/index.htm#Introduction