Details about jQuery Form Verification plug-ins -- Validation, jquery -- validation

Source: Internet
Author: User
Tags valid email address

Details about jQuery Form Verification plug-ins -- Validation, jquery -- validation

Overview

The jQuery Validate plug-in provides powerful form verification functions to simplify form verification on the client side. It also provides a large number of custom options to meet various application needs. This plug-in is bundled with a set of useful verification methods, including URL and email verification, and provides an API for Writing user-defined methods. All bundling methods use English as the error message by default and have been translated into 37 other languages. This plug-in was compiled and maintained by J örn Zaefferer. He is a member of the jQuery team, the main developer of the jQuery UI team, and the maintenance personnel of QUnit. This plug-in started to appear in early jQuery in 2006 and has been updated to date. Visit the official jQuery Validate website to download the latest jQuery Validate plug-in.

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

Basic syntax

The Validate plug-in requires jQuery, so we need to introduce the jQuery and Validate files in the header.

 <script type="text/javascript" src="lib/jquery.js"></script> <script type="text/javascript" src="dist/jquery.validate.min.js"></script>

After the file is introduced, write a simple form.

<Form class = "cmxform" id = "commentForm" method = "get"> <fieldset> <legend> verify the complete form </legend> <p> <label for =" firstname "> name </label> <input id =" firstname "name =" firstname "type =" text "> </p> <label for =" lastname"> last name </label> <input id = "lastname" name = "lastname" type = "text"> </p> <label for = "username"> User name </label> <input id = "username" name = "username" type = "text"> </p> <label for = "password"> password </ label> <input id = "password" name = "password" type = "password"> </p> <label for = "confirm_password"> verify the password </label> <input id = "confirm_password" name = "confirm_password" type = "password"> </p> <label for = "email"> Email </label> <input id = "email" name = "email" type = "email"> </p> <label for = "agree"> Please agree with our statement </label> <input type = "checkbox" class = "checkbox" id = "agree" name = "agree"> </p> <input class = "submit" type = "submit" value = "submit"> </p> </fieldset> </form>

Then we begin to write the verification form code.

First, we need to know that the form needs to be verified.

 $(function(){ $('#commentForm').validate(); });

Then write the validation rules. Note that the selection element is selected based on the name attribute of each label. The basic syntax is as follows:

$ ('# CommentForm '). validate ({rules: {firstname: 'required', // required indicates the required field lastname: {required: true, minlength: 3 // The minimum length is 3 }}});

It can be seen from the above that if one piece of information has only one verification requirement, it can be written as one line, such as firstname; If there are multiple verifications, it should be written in the form of imaging lastname; it knows the basic syntax

Let's take a look at the Validation rules provided by Validation.

(1), required: true mandatory field (2), remote: "remote-valid.jsp" use ajax method to call the remote-valid.jsp to verify the input value (3), email: true: You must enter the email in the correct format (4). url: true: You must enter the url in the correct format (5). date: true: You must enter the date in the correct format. The date validation ie6 has an error, use with caution (6), dateISO: true must enter the date in the correct format (ISO), for example: 2009-06-23,1998/01/22 only verify the format, not verify the validity (7), number: true: a valid number (negative number, decimal number) (8), digits: true, an integer (9), creditcard: true, a valid credit card number (10), and credit: "# password" must be the same as # password (11), accept: enter a string with a valid suffix (12), and maxlength: 5. A string with a maximum length of 5 (one character for Chinese characters) (13), minlength: 10, a string with a minimum length of 10 (one character for Chinese characters) (14), and rangelength: [5, 10] The input length must be a string between 5 and 10 ") (one character for Chinese characters) (15), range: [5, 10] The input value must be between 5 and 10 (16), max: 5, and min: 10. The input value cannot be greater than 5 (17), or 10.

Complete the above form verification, as shown below:

$(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:

We can see that the prompt here is not satisfactory in English by default. There are two ways to change the prompt information to Chinese.

Method 1: introduce language files (recommended)

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

The prompt message is:

Required: "This is a required field", remote: "correct this field", email: "enter a valid email Address", url: "enter a valid url ", date: "enter a valid date", dateISO: "enter a valid date (YYYY-MM-DD)", number: "enter a valid number", digits: "Only numbers can be entered", creditcard: "enter a valid credit card number", cannot to: "your input is different", extension: "enter a valid suffix", maxlength: $. validator. format ("up to {0} characters can be entered"), minlength: $. validator. format ("at least {0} characters must be entered"), rangelength: $. validator. format ("enter a string between {0} and {1}"), range: $. validator. format ("enter a value ranging from {0} to {1}"), max: $. validator. format ("enter a value not greater than {0}"), min: $. validator. format ("enter a value not less than {0 ")

Method 2: Write the prompt information by yourself

$ ('# 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, failed to: '# password'}, email: {required: true, email: true }}, messages: {firstname: "enter your name", lastname: "Enter your last name", username: {required: "Enter your username ", minlength: "The user name must consist of two letters"}, password: {required: "enter the password", minlength: "The password length cannot be less than five letters"}, confirm_password: {required: "enter the password", minlength: "The password length cannot be less than five letters", failed to: "Two different passwords"}, email: "Enter a correct email address ",}});

Effect:

Note:Another write verification method is to write in the class, for example

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

However, this method is not recommended because it does not meet the style and structure separation requirements, and you need to download a jquery. metadata. js file to write this method.

Form submission problems

You can execute custom code before submitting the form. After the custom code is executed, submit the form.

$ ('# CommentForm'). validate ({submitHandler: function () {alert ("event submitted successfully"); from. submit ();}});

You can set the default value of validate.

$. Validate. setDefaults ({submitHandler: function () {alert ("submitted successfully! "); Form. submit ();}});

Verify only the form not submitted

 $(function(){ $("#commentForm").validate({ debug:true; }); });

Error message settings

1. Set the location of the error message

ErrorPlacement is used to set where error messages are displayed. The default value is after the verification element.

 errorPlacement: function(error, element) {  error.appendTo(element.parent());  }

ErrorClass is the style for setting error messages, followed by the css Class Name

ErrorElement is used to set the label used to wrap the error message. The default value is <label>

ErrorLabelContainer is used to set all error messages to one location.

Wrapper is used to set the label and then package the preceding errorELement.

For example:

 errorPlacement: function(error,element){ $(element).closest('form').find('label[for="'+ element.attr("id") +'"]').append(error); },

Displays the error message before the verification information.

Effect:

For example:

 errorElement: 'span', errorClass: 'commentError', errorLabelContainer: $('form div.error'), wrapper: 'li',

Is to wrap each prompt information with the <span> label and add them the css name. the commentError style, and package all of them into a div with the class being error. Use <li> to package each prompt information.

Effect:

2. Set error message styles

There are two ways to modify the style of the prompt information

The first method is to use the style file that comes with the Validation download.

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

The second method is to customize the style (of course, you can also modify the built-in css file)

For example, add a style as follows:

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:

Verification problems

1. Verify that the elements pass

If you want to perform operations when the verified element passes the verification, you can use success, which can accept strings or functions, and add styles when receiving strings.

For example:

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

When the element to be verified passes the verification, 1 is displayed.

For example:

success: "valid"   

Is to add the css style name. valid to the element

2. Verification Method

Custom Verification

Although Validation provides many verification methods, it is not enough in some cases. Therefore, if you want to add a custom verification method, you can use the addMethod method.Write in the additional-methods.js and then introduce this file

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

WriteContents 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 enter your zip code correctly ");

You just need to write this code into the additional-methods.js file and you can use it.

For example:

 zipcode: { required: true, isZipCode :true }

Effect:

Radio, checkbox, and select Verification

Radio required indicates that one of

In the checkbox, required indicates that the number must be selected, minlength indicates the minimum number to be selected, maxlength indicates the maximum number to be selected, and rangelength [2, 3] indicates the selected number range.

Select required indicates that the selected value cannot be blank, minlength indicates the minimum number of required items, maxlength indicates the maximum number of required items, and rangelength [2, 3] indicates the selected number range

Summary:The Validation plug-in provides many verifications. Users can add their own verification and prompt information styles. However, I did not mention ajax-related content in my blog, because ajax has not learned-_-|. If you have any questions, please contact me. If you have any questions, please correct me.

The above is all the content of this article. I hope this article will help you in your study or work. I also hope to provide more support to the customer's home!

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.