jquery Verification Plug-in Validate use method detailed _jquery

Source: Internet
Author: User
Tags html form

1. Written in front

We know that when the user registers, there will be a form page, and then some of the options are required, and some of the content to be filled with a specification, which should be verified before the user submitted to the line, if not meet the requirements, need to display a friendly prompt on the right, let users modify.
Remember before learning the servlet, the implementation of a simple user registration function of the verification is done in the background, some use regular expression, some useless, but are relatively simple. The process is like this, the front desk submits the data, the servlet obtains the data to verify first, if does not meet the request, puts the prompt information in a list, then saves the list to the session, jumps to a new page does the echo, the error message also displays, but is more tedious.
In front of doing online shopping mall project, with Easyui to do background merchandise add, also did the function of verification, easyui with the function of verification, or very powerful, the effect is good. If you are interested, you may wish to take a look at this article.
But what do we do with the page that the front desk user registers? This is the main content of this article, we can use jquery Validate plug-in to do registration verification function, jquery I have no system to learn, just use what to learn what, what to understand, so if there is a mistake, please comment ~ Below I step-by-step through the code to explain the use of jquery-validate verification plug-in procedures.

2. Effect display

First look at the final implementation of the effect, first have a intuitive feeling, personal feeling can be accepted.

As you can see from the diagram, the ability to enter the correct and incorrect prompts, including the prompts before entering, has been completed. Take another look at my project:

A total of 6 JSP files, the reason is written 6 for step-by-step explanation to do this effect of the steps, and finally terminal.jsp is the final version. When running, you only need to run this terminal.jsp. Let me analyze the process of using jqurey-validate to verify the plug-ins in detail.

3. The Validate environment constructs

Environment building, certainly not without jar bag, I am using jquery-validate-1.15, the official gave a few versions of the jquery, I jQuery-1.11.1. So put the two JS files into the project Webroot/js, and in the JSP page can be imported.

Demo1.jsp is very simple, in order to build the environment, if you click Submit, will not jump to the specified page indicates that the environment was built successfully.

4. Use of validate basic methods

Well, the environment was built, and then we started using Validate's basic approach, Here also to import a JS file: Additional-methods.js, the new version of the jquery-validate-1.15 did not verify the file suffix, then I checked on the official web site, the official online said to put in the additional-methods.js, so I went to the next, Put in the project, and the method name is not the same as the old version, the following. Take a look at demo2.jsp:
<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%>

<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >  

Demo2, we have written some basic forms, and in JS to verify it, validate defined some default validation, required represents a required field, rangelength representing the length range, using an array to represent the range boundary, Equalto followed by an ID, which means the same as the following ID element content, here is a extension, said the suffix, the previous version is called Accept, the new version of the extension, the search on the Internet to verify the suffix is accept, the new version is gone, and extension is in the additional-methods.js of the new addition. Let's look at the effect of this version:

A little ugly ... Because has not done CSS, but I directly click on the submission, there will be some validation information, these are the default information, is provided in the source code, stating that the verification function is in effect, we will rewrite the following information, these defaults are obviously not very friendly.

5. Implement localization of error messages

We can specify the display content of the messages message, which is also in JSON format, as follows:
<%@ page language= "java" import= "java.util.*" pageencoding= " UTF-8"%>

<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >  

Equivalent to overwrite the original default message hint, look at the effect:

That's a bit of a feeling. continue to improve.

6. Implement Remote Authentication

The so-called Remote authentication, refers to when users enter the user name registration, the system has to query from the database has the user name, if there is a user has already registered the name, but we do not have to check the database, we write an action simulation can be, The main is to implement the communication between the validate plug-in and the action. See demo4.jsp:

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >  

We see a new remote method in Sname, which is used to authenticate remotely, the parameter URL is the request action to send, so we write a ajaxaction backstage, write a check method in Ajaxaction, Determines whether the username is admin and, if so, returns false in the form of a stream, and the foreground receives false to verify the failure, and returns true to verify success. Failed to tell the user that the user name already exists, background action here will not write, see I uploaded the source code can be. Let's look at the effect:

7. Custom Validation method 

We can also customize the method of verification, such as mobile phone number, we can define their own verification methods, we define the best way to write in the extension JS, we write a jquery.validate.extend.js to the JS folder, in the file written:

Custom method, complete the verification of the phone number
//name: The name of the custom method: function body, message: Error messages
$.validator.addmethod ("Phone", function (value , element, param) {
 //method with three parameters: value: The validated value, element: The currently validated DOM object, param: Parameter (multiple is an array)
 //alert (value + "," + $ ( Element). val () + "," + param[0] + "," + param[1]);
 return new RegExp (/^1[3458]\d{9}$/). Test (value);

}, "Incorrect cell phone number");

Addmethod represents the new method, the first parameter is the method name, the second parameter is the function body, and the third parameter represents the validation error message. In the function body, there are three parameters, value represents the validated value, element represents the current DOM object, and Param represents the parameter. We used regular expressions to verify the phone number. There's no testing here. Finally, we take a look at the final form validation, the ultimate validation form needs to be added CSS, the following is the complete final validation code.

8. Verify the form full version

8.1 HTML Form

To make the form structure simple and clear, we wrap each element of the form in a DIV structure: using a label label to mark the name of the element, and then the form element itself. "NOTE: 1. The advantage of using label labels is that they improve usability for the user of the mouse. When you click Text within a LABEL element, the browser automatically shifts the focus to the form control associated with the label. 2. Each form element that needs to be validated should have the ID and name attribute set to facilitate the binding of the element to the validation rule and checksum information when using the plug-in. 】

The form implementation code is as follows:

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >  

8.2 Form Validation js logic

Then we use JS to achieve the verification of the form elements. Before checking, I extended the jquery validate plug-in to overwrite the default options. The jquery validate plugin defaults to only the correct and error-proofing prompts, and lacks our usual help tips. To solve this problem, I studied the source code of the plug-in, found that the plug-in itself provides onfocusin (the checksum element gets the focus of the call) and Onfocusout (when the checksum element loses focus) these two functions. By modifying these two interfaces of the default parameters, you can implement the party user to click or select elements (that is, the element gets the focus), prompt help information, and remove help information when the user mouse leaves the element (that is, the element loses focus).
In addition, the jquery validate defaults to provide real-time validation of form element input, because we require that only the user help information be turned on when input, so we need to turn off the real-time checksum of the input, so we set the onkeyup in the default parameter to NULL.
Specific extensions to improve the code I put into the new JS script jquery.validate.extend.js, the code is as follows:

/************************* plug-in new feature-sets the default parameter of the plugin validator *****************************************/$. Validator.setdefaults ({*/* real-time check/onkeyup:null when keyboard input is turned off,/* Add validation after successful execution function--Modify the hint content and add a new style for the correct prompt (default is valid) * * Success:
 The default correct style for function (label) {/*label is valid, which needs to be reset by Validclass, otherwise the other styles added here cannot be cleared/Label.text (""). AddClass (' valid '); },/* Rewrite the validation element after the focus of the execution function-increase [1. Help tip when the cursor moves into the element, 2. Highlight of the checksum element] Two function points/onfocusin:function (element) {this.lastactive = element

 ;
 /*1. Help hint function */this.addwrapper (this.errorsfor (Element)). Hide ();
 var tip = $ (Element). attr (' tip ');
 alert (TIP); if (Tip && $ (Element). Parent (). Children (". Tip"). Length = = 0) {$ (Element). Parent (). Append ("<label class="
 Tip ' > ' + Tip + "</label>");

 /*2. Validation element highlighting/$ (element). addclass (' highlight '); Hide error label and remove error class on focus if enabled if (this.settings.focusCleanup) {if this.settings.un Highlight) {This.settings.unhighlight.call (this, element, This.settings.errorClass, this.settingS.validclass);
 } This.hidethese (Element) (this.errorsfor); },/* Overrides the execution function when the focus of the checksum is left-remove [1. Added help hint, 2. Validation element highlighting]*/Onfocusout:function (element) {/*1. Help message removal/$ (element). Pare

 NT (). Children (". Tip"). Remove ();

 /*2. Verify element Highlight style remove/$ (Element). Removeclass (' highlight ');

 /*3. Replace the original code of the following annotation, any time the cursor leaves the element to trigger the checksum function///this.element (element); if (!this.checkable (Element) && (element.name in this.submitted | |!this.optional (Element)) {This.eleme
 NT (Element);

}
 }
}); Custom method, complete the verification of the phone number//name: The name of the custom method: function body, message: Error messages $.validator.addmethod ("Phone", function (value, element, param) {//method has three parameters: value: Validated value, element: Currently validated DOM object, param: Parameter (multiple is array)//alert (value + "," + $ (Element). val () + "," + para
 M[0] + "," + param[1]);

return new RegExp (/^1[3458]\d{9}$/). Test (value);

 "The cell phone number is not correct");

8.3 Form Validation CSS styles

Finally, add CSS styles to the page elements. There are a series of default options in the plug-in: the default error is to display a label and the error style is label.error. Above in the Jquery.validate.extend.js file, there is a success function to explain. This function is executed when the checksum is successful, and we add a checksum-correct style label.valid to the label hint tag in the function. Therefore, if you want to beautify the information in CSS, you need to design a label-related style such as error,valid style. In addition, we have added a label label with class tip in the extension functionality that is generated only when the validation element has the focus. To do this, you also need to set the tip style for the label.
The complete style file content is as follows:

body{Font-family:microsoft Yahei;
font-size:15px;

} fieldset{width:650px;}
 legend{Text-align:center;
font-size:20px;
 }. item{height:56px;
 line-height:30px;
margin:10px;
 }. Item. item-label{Float:left;
 width:80px;
Text-align:right;
 }. item-text{Float:left;
 width:240px;
 height:30px;
 padding:9px 25px 9px 5px;
 margin-left:10px;
 border:1px solid #ccc;
Overflow:hidden;
 }. item-select{Float:left;
 height:30px;
 border:1px solid #ccc;
 margin-left:10px;
 font-size:14px;
PADDING:6PX 0px;
 }. item-file{Float:left;
 height:30px;
 margin-left:10px;
 font-size:14px;
PADDING:6PX 0px;
 }. item-submit{Float:left;
 height:30px;
 width:50px;
 margin-left:90px;
font-size:14px;

input.error{border:1px solid #E6594E;}

input.highlight{border:1px solid #7abd54;}
 label.error{Float:left;
 height:30px;
 line-height:30px;
 font-size:14px;
 Text-align:left;
 margin-left:5px;
 padding-left:35px;
 color:red; Background: URL ('..
/image/error.png ') No-repeat left center;
 } label.tip{Float:left;
 height:30px;
 line-height:30px;
 font-size:14px;
 Text-align:left;
 margin-left:5px;
 padding-left:35px;
 Color: #aaa; Background:url ('..
 /image/tip.png ') No-repeat left center;
padding-left:35px; } label.valid{Background:url ('..
/image/valid.png ') No-repeat left center;

 }

At this point, the form verification is done, here is no longer show, look at the front can be. Effect can also, but can be more perfect, I do not know about jquery is not too much, I hope we make progress together!

SOURCE Download: Verify plugin Validate

Original address: http://blog.csdn.net/eson_15/article/details/51497533

The above is the entire content of this article, I hope to give you a reference, but also hope that we support the 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.