Continue previous articleArticleUse jquery. Validate for client verification (Advanced article-I). This article will continue to introduce jquery. Validate's advanced application-Ajax verification and simple extension of jquery. Validate.
Today, we will introduce the following content:
1. How to Use jquery. Validate for Ajax verification?
2. By default, jquery. Validate must be of the bool type returned during Ajax verification. How to return an object including the error message and verification result?
3. When jquery. Validate is repeatedly used for Ajax verification, relevant Ajax parameters are always required. can we further encapsulate them?
First: How to Use jquery. Validate for Ajax verification? (See High-2.aspx for details)
Jquery. validate provides us with a convenient Ajax verification method (which encapsulates jquery's Ajax and combines jquery's Ajax and jquery. validation of validate works well together). Here I will only introduce jquery. validate in ASP. for details about how to perform Ajax verification under. For details about PhP and JSP, refer to the official example.
I use jquery. Validate + WebService for Ajax verification. The client writes the remote verification attribute of jquery. Validate, and the server uses webserice for receiving parameter verification.
First, let's take a look at how to compile Ajax verification rules for the remote attribute of jquery. Validate:
Function initrules () {opts = {rules: {<% = txtuid. uniqueid % >:{ required: True, remote: {type: "Post", async: false, URL: "WebService. asmx/checkuid ", datatype:" XML ", data: {uid: function () {return jquery (" # <% = txtuid. clientid %> "). val ();}}}}}}}
If you have used jquery. Ajax, you will be familiar with this section.Code, Jquery. Validate Remote uses the same parameter settings as jquery. Ajax (the reason is the reason that jquery. Ajax is encapsulated above ).
Here we will explain in detail some of jquery. Validate's remote knowledge:
1. jquery. by default, the Remote Authentication address of validate can be entered directly. The format is: Remote: "validate. aspx ", but in many cases this remote verification requires the submission of parameters, return type and other restrictions, so you can write specific attributes in" {} "to wrap the submission parameters.
2. In jquery. Validate's remote official code, the remote output can only be true or false, and other outputs are not allowed. I think this is not very good,The specific extension will be discussed later..
3. When using jquery. Validate remote, if you want to submit parameters, you must submit the parameters in JSON format as follows:
Data: {uid: function () {return jquery ("# <% = txtuid. clientid %>"). Val ();}}
Some people may not understand why the parameter needs to be submitted in the form of a function, rather than directly writing
Jquery ("# <% = txtuid. clientid %>"). Val ();
Here I want to explain: jquery. the validation rule of validate is already loaded when the page is loaded. If you still write "jquery (" # <% = txtuid. clientid %> "). val (); ", the data submitted to the server during verification is always the value of the txtuid Control During page loading.
The benefit of using function is that when loading a page, it only tells jquery. validate: Call the function when the control requires remote verification. This ensures that the latest value can be obtained during remote verification.
I also modified the remote method of jquery. Validate. Let's take a look at the modified Code (For details, see scripts/jquery. validate1.js line 896.):
If (Previous. Old! = Value) {previous. old = value; var validator = this; this. startrequest (element); var data ={}; data [element. name] = value; $. ajax ($. extend (true, {// URL: URL, // This URL cannot be obtained URL: Param. URL, // obtain the path mode: "Abort", Port: "Validate" + element in the param verification rule. name, type: Param. type, datatype: "JSON", // data: data, data: Param. data | data, // get Param. parameter success submitted in data or data: function (response) {omitted below ...}
Here, I modified the URL and data acquisition method, mainly because the variable URL is empty during actual execution, so it needs to be obtained from Param.
The main reason why data should be changed to Param. Data | data is the following code:
Data [element. Name] = value;
The Code indicates that the value of the control is obtained when the remote verification is set for the control, but in actual development, when Ajax verification is performed, multiple data needs to be submitted at the same time. In this case, this code is incorrect, so you need to change it
Param. Data | data. This ensures that multiple data types are used when multiple data types are submitted.
Let's take a look at the WebService code:
[Webmethod] public bool checkuid (string UID) {return uid = "testuid "? True: false ;}
It is quite simple to determine whether the user name is the specified user name.
Note: In WebService. CS, you must uncomment the [system. Web. Script. Services. scriptservice] feature. Otherwise, Ajax verification will be ineffective!
Second point:By default, jquery. Validate must be of the bool type returned during Ajax verification. How to return an object including error messages and verification results? (For details, see app_code/WebService. CS/checkuid.)
The first part introduces jquery. the knowledge of validate was mentioned, jquery. by default, validate directly accepts "true" or "false", but in specific development, we will perform hierarchical development, layer-3 or multi-layer development, after receiving the verification request, WebService directly calls the verification method at the logic layer, and submits it to the logic layer for verification (Of course, you can also write all the verification in WebService, but this does not reflect the advantages of layering.In this case, the verification will generate multiple situations. Take the most common user name verification as an example:
1) The user name already exists, and the message should be"The user name already exists. enter a new one.!"
2) The user name does not comply with the rules. The message should be"The user name does not comply with the rules. enter a new one.!"
3) VerificationProgramException. The message should be"Program exception. Contact the administrator.!"
It can be seen that only one User Name authentication will display these three types of information. If no clear message is returned, it will only tell the user that "the user name is incorrect", and the user on the client will be quite painful, because the user does not know where the input of his username is wrong.
Therefore, for better customer experience and project rationality, we encapsulate an entity class (For details, see appcode/ajaxclass.), The Code is as follows:
[Serializable] public class ajaxclass {Public String MSG {Get; set;} public int result {Get; Set ;}}
It is the simplest entity class with two attributes: MSG and result. MSG is used to store information about verification failures and result is used to store results.
See how to modify the webserivce code:
[Webmethod] public ajaxclass checkuid (string UID) {// return uid = "testuid "? True: false; ajaxclass = new ajaxclass (); try {If (uid = "testuid") {ajaxclass. MSG = "the user name already exists. Please enter it again! "; Ajaxclass. result = 0;} else if (UID. indexof ("test") =-1) {ajaxclass. MSG = "the username format is incorrect. The username must contain test. Please enter it again! "; Ajaxclass. Result = 0;} else {ajaxclass. MSG =" The format is correct! "; Ajaxclass. Result = 1 ;}} catch {ajaxclass. MSG =" The program encountered an exception. Please contact the administrator! "; Ajaxclass. Result = 0;} return ajaxclass ;}
The preceding WebService fully implements the three errors I mentioned earlier (As this is just an example, only the presentation layer is available. In actual development, hierarchical development is required. This code should be placed in the business logic layer.)
Note: Before the WebService return value, if the check succeeds, it must be ajaxclass. Result = 1. Otherwise, the client cannot pass the verification.
Although the Code Modification on the server is completed, an error occurs when running the page directly. This is because of the jquery. the remote output of validate can only be true or false. Let's look at the specific code. The original official code is commented out:
Success: function (response) {If (response. result) {// If (response) {var submitted = validator. formsubmitted; validator. prepareelement (element); validator. formsubmitted = submitted; validator. successlist. push (element); validator. showerrors () ;}else {var errors ={}; // errors [element. name] = response. result | validator. defaultmessage (element, "remote"); errors [element. name] = response. MSG; validator. showerrors (errors);} previous. message = response. MSG; // previous. valid = response; previous. valid = response. result; validator. stoprequest (element, response. result );}
We can see that there are three changes:
1. Determine the return value. Originally, response is directly judged, and now response. result is judged, because the current response is already an object containing messages and results.
2. error message: the original error message directly obtains the default message, which is response. MSG.
3. Set the previous object and set the messages and results of the previous object to the messages and results returned by Ajax for the code returned by jquery. Validate.
Jquery. the remote method of validate is modified, but it is not completed because jquery. because of the validation rules of validate, the submitted parameters are not submitted in JSON format but in the format of {uid: function ()}. As a result, jquery cannot be set. ajax contenttype: "application/JSON; charset = UTF-8". The following error occurs if it is set:
In this way, the ajaxclass object returned from WebService cannot be directly operated in JSON format, so we can only change the format-XML, because the data returned by WebService is in XML format by default:
<? XML version = "1.0" encoding = "UTF-8"?> -<Ajaxclass xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: XSD = "http://www.w3.org/2001/XMLSchema" xmlns = "http://tempuri.org/"> <MSG> the username format is incorrect and the username must contain test, enter again! </MSG> <result> 0 </result> </ajaxclass>
Next, let's take a look at how to compile the specific remote method,Set datatype: "XML" and convert the XML data into an object for ajaxsuccess in the remote method of jquery. Validate I modified above.Take a look at the Code:
Remote: {type: "Post", datatype: "JSON", async: false, URL: "WebService. asmx/checkuid ", data: {uid: function () {return jquery (" # <% = txtuid. clientid %> "). val () ;}, datafilter: function (dataxml) {var result = new object (); result. result = jquery (dataxml ). find ("result "). text (); result. MSG = jquery (dataxml ). find ("MSG "). text (); If (result. result = "-1") {result. result = false; return result;} else {re Sult. Result = result. Result = "1 "? True: false; return result ;}}}
Jquery. the Ajax method datafilter can filter and process the data after the Ajax request is successful. Here I use the jquery method to retrieve the results and messages from the XML and assign them to an object directly, then, the object is returned and used by ajaxsuccess.
In this way, the remote method of jquery. Validate is modified, so that the verification result and verification message can be returned. For details, refer:
Third point:When jquery. Validate is repeatedly used for Ajax verification, it is always necessary to write relevant Ajax parameters. Can it be further encapsulated? (For details, see High-3.aspx and jquery. Validate. extension. JS)
Ajax verification is often used when developing a system. It is inconvenient to write the above Code every time, so I will perform simple encapsulation now, the Code is as follows:
// Remote verification abstract method function getremoteinfo (posturl, data) {var remote = {type: "Post", async: false, URL: posturl, datatype: "XML", data: data, datafilter: function (dataxml) {var result = new object (); result. result = jquery (dataxml ). find ("result "). text (); result. MSG = jquery (dataxml ). find ("MSG "). text (); If (result. result = "-1") {result. result = false; return result;} else {result. result = result. res Ult = "1 "? True: false; return result ;}}; return remote ;}
This function mainly receives two parameters. One is the path for remote verification and the parameters to be submitted, and the encapsulated remote object is returned.
The page call is also simple. The Code is as follows:
<SCRIPT src = "scripts/jquery. validate. extension. JS "type =" text/JavaScript "> </SCRIPT> <SCRIPT type =" text/JavaScript "> function initrules () {var datainfo = {uid: function () {return jquery ("# <% = txtuid. clientid %> "). val () ;}}; var remoteinfo = getremoteinfo ('webservice. asmx/checkuid ', datainfo); opts = {rules: {<% = txtuid. uniqueid % >:{ required: True, remote: remoteinfo }}</SCRIPT>
How is it? Compared with the above Code, is it much cleaner?
You only need to perform three steps on the page:
1. Wrap the data objects to be submitted.
2. Pass the Remote Authentication address and encapsulated data object to the encapsulated method to obtain the remote object.
3. Add the remote object returned by the function to the rule.
Jquery. validate for client verification-the reason for not using Microsoft to verify the control, even if all of this series are completed, jquery is generally used. validate in ASP. some common applications on net are introduced, and I also put forward a lot of self-modified extensions. I hope it will help my friends who are worried about client verification. Thank you for your support!
PS: 1. In fact, this series does not cover all the functions of jquery. Validate, such as onfocusin, onfocusout, and onkeyup. You need to view them during usage.Source codeExperiment.
2. This Article is a bit long and has a lot of content. If you have any mistakes or have any guidance, please submit it. Thank you!
Source code download: Click here to download