Detailed jquery form Verification plug-in--validation_jquery

Source: Internet
Author: User
Tags valid email address wrapper

General Introduction

The JQuery Validate plug-in provides a powerful validation feature for forms, making client form validation simpler, while providing a wide range of customization options to meet the needs of the application. The plug-in bundles a set of useful authentication methods, including URL and email authentication, while providing an API for writing user-defined methods. All bundled methods use English as an error message by default and are translated into 37 other languages. The plugin is written and maintained by Jörn Zaefferer, a member of the jquery team, the main developer of the jquery UI team, and a qunit maintenance person. The plugin began appearing early in 2006 in JQuery and has been updated ever since. Visit the jquery Validate website and download the latest version of the jquery Validate plugin.

Download Address: Http://wd.jb51.net:81//201612/yuanma/jquery-validation-1.14.0_jb51.rar

Basic syntax

Validate Plug-ins require jquery, so we need to introduce jquery and validate files in the head

 <script type= "Text/javascript" src= "lib/jquery.js" ></script>
 <script type= "Text/javascript" src = "Dist/jquery.validate.min.js" ></script>

File introduced, write a simple form first

<form class= "Cmxform" id= "Commentform" method= "get" > <fieldset> <legend> validate complete Form </legend>
 <p> <label for= "FirstName" > Name </label> <input id= "FirstName" name= "FirstName" type= "text" > </p> <p> <label for= "LastName" > Last name </label> <input id= "LastName" Name= "LastName" type= "text" > </p> <p> <label for= "username" > user name </label> <input id= "username" name= "username" type= " Text "> </p> <p> <label for=" password "> Password </label> <input id=" password "name=" password "ty pe= "Password" > </p> <p> <label for= "Confirm_password" > Authentication password </label> <input id= "confirm_ Password "name=" Confirm_password "type=" password "> </p> <p> <label for=" email ">email</label&
 Gt <input id= "Email" name= "email" type= "email" > </p> <p> <label for= "Agree" > Please agree to our statement </label&
 Gt <input type= "checkbox" class= "CHeckbox "id=" Agree "Name=" agree "> </p> <p> <input class=" Submit "type=" Submission "value=" submitted "> </p > </fieldset> </form>

And then we start writing the code that verifies the form.

First we need to know that the form needs to be validated

 $ (function () {
 $ (' #commentForm '). Validate ();
 

Then start writing the validation rules, notice that the selection element is selected based on the name attribute of each tag, and the basic syntax is as follows

$ (' #commentForm '). Validate ({
 rules: {
 FirstName: ' Required ',//required representation is a required field
 LastName: {
 Required:true,
 minlength:3//Minimum length is 3
 }}}
 );

As can be seen from the above, if a message has only one authentication requirement can be written in one line, such as FirstName; if there are multiple validations to be written like LastName; know the basic syntax

Look at the validation all provide those checksum rules

(1), Required:true required field
(2), Remote: "remote-valid.jsp" using the Ajax method call remote-valid.jsp validation input value
(3), email:true Must enter the correct format of the e-mail
(4), url:true must enter the correct format of the URL
(5), date:true must enter the correct format of the date, the date check IE6 error, use caution
(6), dateiso:true You must enter the correct format for the date (ISO), for example: 2009-06-23, 1998/01/22 only verify the format, not verify validity
(7), number:true must enter a valid number (negative, decimal)
(8), digits:true Must enter integer
(9), creditcard:true must enter legal credit card number
(10), Equalto: "#password" input value must be the same as #password
(11), Accept: Enter the string with the legal suffix name (the suffix of the uploaded file)
(12), the Maxlength:5 input length of up to 5 (Chinese characters)
(13), the Minlength:10 input length of the minimum 10 of the string (Chinese character)
(14), rangelength:[5,10] Enter a string that must be between 5 and 10 in length ") (Chinese characters are counted as one character)
(15), range:[5,10] input value must be between 5 and 10
(16), Max:5 input value cannot be greater than 5
(17), min:10 input value cannot be less than 10

We'll refine the form above, as follows

$ (function () {
 $ (' #commentForm '). Validate ({
 rules: {
 firstname: {
 required:true,
 minlength:5
 },
 LastName: "Required",
 Username: {
 required:true,
 rangelength: [4,6]
 },
 Password: {
 required:true,
 minlength:4,
 number:true
 },
 Confirm_password: {
 Required:true,
 minlength:3,
 equalto: ' #password '
 },
 email: {
 required:true,
 email: True
 },
 }
 });
 

Effect:

You can see that the hint here defaults to English is not very satisfactory, there are two ways to change the message into Chinese

The first way: Introduce language files (recommended)

<script type="text/javascript" src="dist/localization/messages_zh.js"></script>

His cue message is:

Required: "This is a required field",
 remote: "Please fix this field",
 email: "Please enter a valid email address",
 URL: "Please enter a valid URL",
 Date: "Please enter a valid date", Dateiso: "Please enter a
 valid date (YYYY-MM-DD)",
 number: "Please enter a valid digit",
 digits: "Only enter a number",
 creditcard: "Please enter a valid credit card number",
 Equalto: "Your input is not the same",
 extension: "Please enter a valid suffix",
 maxlength: $.validator.format ("can enter {0} characters"),
 MinLength: $.validator.format ("Enter {0} characters at least"),
 rangelength: $.validator.format ("Please enter a string between {0} to {1}"),
 Range: $.validator.format ("Please enter a value between {0} to {1}"),
 Max: $.validator.format ("Please enter a value not greater than {0}"),
 min: $. Validator.format ("Please enter a value not less than {0}")

The second way: Write your own cue messages

$ (' #commentForm '). Validate ({
 rules: {
 firstname: {
 required:true,
 minlength:5
 },
 LastName: "Required",
 Username: {
 required:true,
 rangelength: [4,6]
 },
 password: {
 Required:true,
 minlength:4,
 number:true
 },
 Confirm_password: {
 required:true,
 Minlength:3,
 equalto: ' #password '
 },
 email: {
 required:true,
 email:true
 }
 },
 messages: {
 firstname: "Please enter your name",
 LastName: "Please enter your last name",
 Username: {
 required: "Please enter username",
 minlength: "Username must be composed of two letters"
 },
 password: {
 required: "Please enter password"
 minlength: "Password length can not be less than 5 letters"
 },
 Confirm_password: {
 required: "Please enter password",
 minlength: "Password length cannot be less than 5 letters",
 Equalto: "Two times password input inconsistent "
 },
 email:" Please enter a correct mailbox ",}
 });

Effect:

Note: Another way to write validation is to write in class, such as

<input id="firstname" name="firstname" type="text" class="{required:true, minlength:2}">

This type of writing is not recommended, however, because it does not conform to the requirements of style and structure separation, and it is necessary to download a jquery.metadata.js file to write

Form submission Issue

You can execute our custom code before the form is submitted, and then submit the form when our custom code has finished executing

$ (' #commentForm '). Validate ({
 submithandler:function () {
 alert ("Commit event succeeded");
 From.submit ();
 }
 );

You can set the default value for validate

 $.validate.setdefaults ({
 submithandler:function () {
 alert ("submitted successfully! ");
 Form.submit ();
 }
 );

Validate only not submitting forms

 $ (function () {
 $ (' #commentForm '). Validate ({
 debug:true;
 });
 });

Error message Settings

1, error message location settings

The Errorplacement method is to set the error message to show where the default value is after the validation element

 Errorplacement:function (Error, Element) { 
 error.appendto (element.parent ()); 
 }

Errorclass is the style that sets the error message, followed by the CSS class name

Errorelement is to set what label to wrap the error message, the default value is <label>

Errorlabelcontainer is set to put all the error messages in one place

Wrapper is to set the label and wrap the top errorelement up.

For example:

 Errorplacement:function (error,element) {
 $ (element). Closest (' form '). Find (' label[for= ' + element.attr ("id") + ' "]". Append (Error);
 },

is to display the error message in front of the authenticated information

Effect:

For example:

 Errorelement: ' span ',
 errorclass: ' Commenterror ',
 errorlabelcontainer: $ (' Form div.error '),
 wrapper: ' Li ',

is to wrap each hint with a <span> tag, and add them a CSS named. Commenterror style, and pack them all into one class for the error Div, with <li> wrap each hint message

Effect:

2. Error message style settings

There are two ways to modify the style of the hint message

The first is to adopt the style file that comes with when downloading validation

<link href="demo/css/screen.css" type="text/css" rel="stylesheet" />

The second way is to define your own style (and, of course, you can modify your own CSS file)

For example, add a style like this:

Input.error {border:1px solid red;}
 Label.error {
 Background:url ("demo/images/unchecked.gif") no-repeat 0px 0px;
 padding-left:16px;
 padding-bottom:2px;
 Font-weight:bold;
 Color: #EA5200;
 }
 label.checked {
 Background:url ("demo/images/checked.gif") no-repeat 0px 0px;
 }

Effect:

Problems with validation

1, the validation of the elements through

Validated elements you can use success if you want to work with validation, he can accept strings or functions, add styles when accepting strings

For example:

 Success:function () {
 alert (1);
 },

is when the element to be validated is validated by a pop-up 1

For example:

success: "valid"   

is to add a CSS style named. Valid to the element

2. Verification method

Custom Checksum

Although validation provides a number of ways to validate, some cases are not enough, so if you want to add a custom checksum using the Addmethod method, you usually write the custom method in Additional-methods.js. And then we're going to introduce this file

 <script type="text/javascript" src="dist/additional-methods.js"></script>

Write The contents of the Additional-methods.js file

For example:

 $.validator.addmethod ("Iszipcode", function (value, Element) { 
 var tel =/^[0-9]{6}$/;
 return this.optional (Element) | | (Tel.test (value);
 }, "Please fill in your zip code correctly");

Just write this code to the Additional-methods.js file and you can use the

For example:

 ZipCode: {
 required:true,
 iszipcode:true
 }

Effect:

Verification of Radio and checkbox, select

Radio's required indicates that you must select a

The required representation of the checkbox must be checked, minlength represents the minimum number that must be selected, MaxLength represents the maximum number that must be selected, rangelength[2,3] indicates the selected range

The required of the select indicates that the selected value cannot be empty, minlength represents the minimum number that must be selected, MaxLength represents the maximum number that must be selected, and rangelength[2,3] indicates the selected range

Summary: Validation Plug-ins provide a lot of validation, users can add their own authentication and hint information style, but in the blog I did not mention Ajax-related content, because Ajax has not learned-_-| |, if there are any problems to discuss with me, if there is a wrong place, please correct me.

The above is the entire content of this article, I hope the content of this article for everyone's study or work can bring some help, but also hope that a lot of support cloud Habitat community!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.