Ajax verification implementation code for jQuery Validation-Engine in ASP. NET

Source: Internet
Author: User
Tags php example

See:

Verification example: http://www.position-relative.net/creation/formValidator/

Official Address: http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/

This plug-in supports most browsers. However, due to the use of css3 shadow and rounded corner styles, corner and shadow effects cannot be seen in IE (IE 9 supports rounded corner effects ).

The main content of this article is: Implement AJAX verification in ASP. NET. The official Ajax verification example is an example of PHP. The documents I consulted on the website are basically translated from the official website. It is no problem to implement normal verification in ASP. NET. However, Ajax verification cannot be implemented. This should be a bug. I have studied the plug-in code and provided my own solution. NET to achieve this effect, you must modify the official main JS file. Of course, you can explore it based on the author's ideas! See:

How can I use this plug-in? I can find a lot of answers using search engines. Here I will give a brief comment to take care of new students. First, we download the plug-in package, which is official.
The plug-in package mainly uses three files:Copy codeThe Code is as follows: jquery. validationEngine. js // plug-in main JS File
Jquery. validationEngine-cn.js // validation rule JS File
ValidationEngine.jquery.css // style sheet File

Of course, this plug-in is a third-party plug-in of jQuery. Therefore, we need to apply the core library of jquery first. I can test jquery 1.4.2 without any problems.
1. Introduce jquery and plug-in js and css filesCopy codeThe Code is as follows: <link href = "Scripts/Validation-Engine/css/validationEngine.jquery.css" rel = "stylesheet" type = "text/css"/>
<Script src = "Scripts/jquery-1.4.1-vsdoc.js" type = "text/javascript"> </script>
<Script src = "Scripts/Validation-Engine/js/jquery. validationEngine. js" type = "text/javascript"> </script>
<Script src = "Scripts/Validation-Engine/js/ages/jquery. validationEngine-zh_CN.js" type = "text/javascript"> </script>

2. initialize the plug-in and add the following code in the head area of the page:
$ (Document). ready (function () {$ ("# formID"). validationEngine (); // formID is the form ID you want to verify })
3. Add form Element verification rules. Common verification rules are described in the official address above, but are in English. Baidu is also recommended. This is not a difficult issue.
<Input id = "Text3" type = "text" class = "validate [required, ajax [ajaxUsers]"/>
Multiple verifications are separated by commas (,).
4. Verification triggerCopy codeThe Code is as follows: $ ("# formID"). validationEngine ({
InlineValidation: false, // modify it here
Success: false,
AlidationEventTriggers: "keyup blur", // A keyup is added here, that is, the verification is triggered when the keyboard is pressed.
PromptPosition: "topRight", // There are five modes: topLeft, topRight, bottomLeft, centerRight, bottomRight
Failure: function () {callFailFunction ()}
})

5. Ajax verification. Well, here is the problem. Before analyzing the problem, let's take a look at how the main Javascript file of Validation-Engine implements Ajax verification. Open the jquery. validationEngine. js file, and press Ctrl + F to find the "$. ajax" file. We need to modify the second one. See the collapsed official source code below,
Key code in the official jquery. validationEngine. js FileCopy codeThe Code is as follows: key code in the official jquery. validationEngine. js File
$. Ajax ({
Type: options. ajaxFormValidationMethod,
Url: rule. url,
Cache: false,
DataType: "json ",
Data: "fieldId =" + field. attr ("id") + "& fieldValue =" + field. val () + "& extraData =" + extraData + "&" + extraDataDynamic,
Field: field,
Rule: rule,
Methods: methods,
Options: options,
BeforeSend: function (){
// Build the loading prompt
Var loadingText = rule. alertTextLoad;
If (loadingText)
Methods. _ showPrompt (field, loadingText, "load", true, options );
},
Error: function (data, transport ){
Methods. _ ajaxError (data, transport );
},
Success: function (json ){
// Asynchronously called on success, data is the json answer from the server
Var errorFieldId = json [0];
// Var errorField = $ ("#" + errorFieldId) [0]);
Var errorField = $ ("input [id = '" + errorFieldId + "']") [0]);
// Make sure we found the element
If (errorField. length = 1 ){
Var status = json [1];
// Read the optional msg from the server
Var msg = json [2];
If (! Status ){
// Houston we got a problem-display an red prompt
Options. ajaxValidCache [errorFieldId] = false;
Options. isError = true;
// Resolve the msg prompt
If (msg ){
If (options. allrules [msg]) {
Var txt = options. allrules [msg]. alertText;
If (txt)
Msg = txt;
}
}
Else
Msg = rule. alertText;
Methods. _ showPrompt (errorField, msg, "", true, options );
} Else {
If (options. ajaxValidCache [errorFieldId]! = Undefined)
Options. ajaxValidCache [errorFieldId] = true;
// Resolves the msg prompt
If (msg ){
If (options. allrules [msg]) {
Var txt = options. allrules [msg]. alertTextOk;
If (txt)
Msg = txt;
}
}
Else
Msg = rule. alertTextOk;
// See if we shoshould display a green prompt
If (msg)
Methods. _ showPrompt (errorField, msg, "pass", true, options );
Else
Methods. _ closePrompt (errorField );
}
}
ErrorField. trigger ("jqv. field. result", [errorField, options. isError, msg]);
}
});

Based on the above analysis, I came to the conclusion that the AJAX verification here is also based on jQuery $. the AJAX () method writes a $. AJAX () to verify jquery. validationEngine. the AJAX method in js.
5.1 Step 1: Create a background processing program. Here, a general processing program is created as an example. The Code is as follows:Copy codeThe Code is as follows: public void ProcessRequest (HttpContext context)
{
Context. Response. ContentType = "text/plain ";
HttpContext _ content = HttpContext. Current;
String validateId = _ content. Request ["fieldId"];
String validateValue = _ content. Request ["fieldValue"];
String validateError = _ content. Request ["extraData"];
String str;
If (validateValue = "abc ")
Str = "{\" jsonValidateReturn \ ": [\" "+ validateId +" \ ", \" "+ validateError +" \ ", true]}";
Else
Str = "{\" jsonValidateReturn \ ": [\" "+ validateId +" \ ", \" "+ validateError +" \ ", false]}";
Context. Response. Write (str );
}

Note: During AJAX verification, three core parameters will be POST to the backend, fieldId, fieldValue, and extraData. Of course, other parameters can be customized and passed.
5.2 Step 2: Create An aspx page and write an AJAX request following the JavaScript code of Validation-Engine. The Code is as follows:Copy codeThe Code is as follows: Demo page
<% @ Page Language = "C #" AutoEventWireup = "true" CodeBehind = "FormValidation. aspx. cs" Inherits = "DemoWeb. FormValidation" %>
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> jQuery form verification-Validation-Engine </title>
<Link href = "Scripts/Validation-Engine/css/validationEngine.jquery.css" rel = "stylesheet" type = "text/css"/>
<Script src = "Scripts/jquery-1.4.1-vsdoc.js" type = "text/javascript"> </script>
<Script src = "Scripts/Validation-Engine/js/jquery. validationEngine. js" type = "text/javascript"> </script>
<Script src = "Scripts/Validation-Engine/js/ages/jquery. validationEngine-zh_CN.js" type = "text/javascript"> </script>
<Script type = "text/javascript">
$ (Document). ready (function (){
$ ("# FormID"). validationEngine ({
AjaxFormValidation: true
});
$. Ajax ({
Type: "get ",
Url: "AjaxBackstage/AjaxValidation. ashx ",
Cache: false,
Data: {"fieldId": "Text4", "fieldValue": "haha", "extraData": "nowtime2012 "},
DataType: "json ",
Error: function (XMLHttpRequest, textStatus, errorThrown ){
Alert ("error! XMLHttpRequest. status = "+ XMLHttpRequest. status +", XMLHttpRequest. readyState = "+ XMLHttpRequest. readyState +", textStatus = "+ textStatus );
},
Success: function (json ){
Alert ("Hello, it's successful! "+ Json. jsonValidateReturn [0] +", "+ json. jsonValidateReturn [1] +", "+ json. jsonValidateReturn [2]);
}
});
});
</Script>
</Head>
<Body>
<Form id = "formID" runat = "server">
<H2>
JQuery-Validation-Engine-Ajax Verification
</H2>
<Br/>
<P>
Ajax: <input id = "Text3" type = "text" class = "validate [required, ajax [ajaxUsers]"/>
</P>
<P>
Ajax: <input id = "Text4" type = "text" class = "validate [ajax [ajaxUsers]"/>
</P>
<P>
Ajax: <input id = "Text1" type = "text" class = "validate [required]"/>
</P>
</Form>
</Body>
</Html>

Demo page
Url: "AjaxBackstage/AjaxValidation. ashx" points to the general processing program just created.
If the data returned by the debugging result is in the correct json format, the function under succes will be executed. Otherwise, the function below error will be executed. The following describes the result.


If an error is returned, the AJAX verification of Validation-Engine cannot be completed. It is shown that the error is a pars error compiler error. The root cause is the data returned problem. The following is the part of the data returned by the background processing program. I tested that the field cannot be enclosed in single quotation marks. Otherwise, the result is displayed. Therefore, the transmitted data is enclosed in double quotation marks.

Copy codeThe Code is as follows: string str;
If (validateValue = "abc ")
Str = "{\" jsonValidateReturn \ ": [\" "+ validateId +" \ ", \" "+ validateError +" \ ", true]}";
Else
Str = "{\" jsonValidateReturn \ ": [\" "+ validateId +" \ ", \" "+ validateError +" \ ", false]}";
// If (validateValue = "abc ")
// Str = "{'jsonvalidatereturn': ['" + validateId + "', '" + validateError + "', true]}";
// Else
// Str = "{'jsonvalidatereturn \": ['"+ validateId +"', '"+ validateError +"', false]} ";

Data Request successful:

Step 3: Use the preceding example to perform an "operation" on the jquery. validationEngine. js file. Refer to the above section 5.3. JsonValidateReturn? Right, the key is here. The official version is a PHP example, And the transmitted json data is slightly different. As a result, json [0] cannot obtain data. In this example, the data obtained by json. jsonValidateReturn [index] is normal. Of course, you do not like the jsonValidateReturn name. You can also define a name, provided that the name is the same as the name here when data is transferred in the background.

Copy codeThe Code is as follows: // the asynchronous call is successful. The data is the JSON answer from the server.
// Change the location. Originally, jvar errorFieldId = json [0] cannot obtain data in asp. Net.
// Change it to the following method. Note that the name of jsonValidateReturn is fixed here and must be consistent with that of jsonValidateReturn when returning data in the AJAX background.
// {"JsonValidateReturn": ["validateId", "validateError", "true"]}
Var errorFieldId = json. jsonValidateReturn [0]; // change location

// Var errorField = $ ("#" + errorFieldId) [0]);
Var errorField = $ ("input [id = '" + errorFieldId + "']") [0]);

// Make sure that we find the element
If (errorField. length = 1 ){
Var status = json. jsonValidateReturn [2]; // change location
// Optional MSG read from the server
Var msg = json. jsonValidateReturn [1]; // change location
If (! Status ){
// Houston, we have a problem-a red prompt is displayed.
Options. ajaxValidCache [errorFieldId] = false;
Options. isError = true;

5.4 Step 4, customize rules in the language file, the Official Language Pack has a Chinese language file called jquery. validationEngine-zh_CN.js, here I add a "ajaxUsers" rule.Copy codeThe Code is as follows: // --- custom rules -- Those are specific to the demos, they can be removed or changed to your likings
"AjaxUsers ":{
"Url": "AjaxBackstage/AjaxValidation. ashx ", //" validate. action "," validate. action "ajax authentication username, post the following parameters: validateError ajaxUser; validateId user; validateValue cccc
"AlertTextOk": "* accounts can be used .",
"AlertTextLoad": "* Checking, please wait ...",
"AlertText": "* The account cannot be used ."
},
"AjaxUserCall ":{
"Url": "ajaxValidateFieldUser ",
// You may want to pass extra data on the ajax call
// "ExtraData": "name = eric ",
"AlertText": "* This name has been used by others ",
"AlertTextLoad": "* verifying whether the name is used by another user. Please wait. "
},

OK. Try to verify if it succeeds...


Finally, we will summarize some experiences and share them with you. "Find the answer to the question from the essence of the thing !".
Note: This article is original. For more information, see the source! Http://www.cnblogs.com/skylinetour/

Related Article

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.