Asp. Implementation of jquery Validation-engine Ajax Verification _ practical skills in net

Source: Internet
Author: User
Tags httpcontext
See figure below:

Example of validation: 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 plugin supports most browsers, but due to the use of the CSS3 Shadow and fillet style, in IE browser can not see the fillet and shadow effects (ie 9 support fillet effect).

The main content of this article is: to implement the Ajax verification function in ASP.net. The official example of AJAX verification is a PHP instance, the author of the information on the website is basically translation of the official website, in the asp.net to achieve common verification is no problem. However, Ajax validation is not possible, and this should be a bug. The author studied the plug-in code, gave me a solution, to achieve this effect in asp.net, must modify the official main JS file, of course, students can be based on the author's thinking to dig, welcome to add! The implementation effect is shown in the following figure:

Specific how to use this plug-in, search engine can find a lot of answers, the author here A simple long-winded, take care of the new students. First of all our download plug-in package, above is the official download address.
Plug-in package we are using three files mainly:
Jquery.validationEngine.js//Plugin main JS file
Jquery.validationengine-cn.js//Validation rules JS file
VALIDATIONENGINE.JQUERY.CSS//Style sheet files
Of course, this plugin is a third party plug-in for jquery, so first of all, to apply jquery's core library, the author test jquery 1.6.1 is no problem.
1. Introduction of jquery and Plug-ins js, CSS files
<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/languages/jquery.validationengine-zh_cn.js" type= "Text/javascript" ></script>
2. Initialize the plugin, add the following code in the page Head area:
Copy Code code as follows:

$ (document). Ready (function () {
$ ("#formID"). Validationengine (); Formid is the form ID you want to verify
})

3. Add form element validation rules, commonly used validation rules above the official address has instructions, but also Baidu, this is not a difficult point.
<input id= "Text3" type= "text" class= "validate[required,ajax[ajaxusers"] "/>
Multiple validation multiple comma separated
4. Validation Trigger
Copy Code code as follows:

$ ("#formID"). Validationengine ({
Inlinevalidation:false,//Modify here
Success:false,
Alidationeventtriggers: "KeyUp blur",//Here added a keyup, that is, the keyboard button to trigger the validation
Promptposition: "TopRight",//There are 5 modes of TopLeft, TopRight, Bottomleft, Centerright, BottomRight
Failure:function () {callfailfunction ()}
})

5.Ajax verification, OK, here is the problem, in the analysis of the problem before we look at the validation-engine main JS file is how to achieve AJAX verification. Open the Jquery.validationEngine.js file, ctrl+f Find in the "$.ajax" document can be found in two places, we want to modify the second, see the following collapsed official source code,
Key code in the official Jquery.validationEngine.js file
Copy Code code 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 + "&" + Extrada Tadynamic,
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 are 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 a 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;
If we should 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]);
}
});

From the above official source code analysis, the AJAX validation mechanism here is also based on jquery $. AJAX () method. To find out what the plugin cannot verify, the author uses jquery to write a $. Ajax () Request to verify the AJAX validation in Jquery.validationEngine.js.
5.1 The first step, create a background handler, here to create a general handler for example, the code is as follows:
Copy Code code 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 here: In the Ajax verification, post three core parameters to the background, FieldID, Fieldvalue, Extradata, of course, can also customize other parameters passed over
5.2 Step Two, create an ASPX page in the Validation-engine JS to write an AJAX request, the code is as follows:
Copy Code code 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 ">
<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/languages/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 ("Wrong!") Xmlhttprequest.status= "+ Xmlhttprequest.status +", xmlhttprequest.readystate= "+ Xmlhttprequest.readystate +", textstatus= "+ textstatus);
},
Success:function (JSON) {
Alert ("Hello, success!") "+json.jsonvalidatereturn[0] +", "+ json.jsonvalidatereturn[1] +", "+ json.jsonvalidatereturn[2]";
}
});
});
</script>
<body>
<form id= "Formid" runat= "Server" >
Jquery-validation-engine-ajax Verification
<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>

URL: "Ajaxbackstage/ajaxvalidation.ashx" here point to the generic handler you just created
The debug result returns the correct JSON-formatted data that executes the function below the succes, otherwise the function below the error is executed, look at the effect

When an error is returned, the Validation-engine Ajax validation cannot be completed. This shows that the error is "Pars error" compiler error, root cause or return data problem. The following is the background handler of the Return Data section, the author tests, the field can not use single quotes, or see the above image effect, so here with the data passed in double quotes.
Copy Code code 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 succeeded:

5.3 The third step, according to the above example to the Jquery.validationEngine.js file dynamic "surgery", refer to the 5th above. Jsonvalidatereturn? Yes, the key is in this place, the official version of PHP is an example of a little difference in the JSON data passed, causing Json[0 to get no data. So in this case Json.jsonvalidatereturn[index] gets the data to be normal. Of course you don't like the name. Jsonvalidatereturn can also define a name yourself, but only if the name in the background is consistent with the name here.
Copy Code code as follows:

The asynchronous call succeeded, the data is from the server's JSON answer
Change the place, originally Jvar Errorfieldid =json[0] in ASP. NET is not getting the data in the
Change to the following way, note Jsonvalidatereturn here the name is dead, in the Ajax background to return data must be consistent with the Jsonvalidatereturn
{"Jsonvalidatereturn": ["Validateid", "Validateerror", "true"]}
var errorfieldid = json.jsonvalidatereturn[0]; Change of place
var Errorfield = $ ($ ("#" + Errorfieldid) [0]);
var Errorfield = $ ($ ("input[id= '" + Errorfieldid + "']") [0]);
Make sure we find the elements.
if (errorfield.length = = 1) {
var status = Json.jsonvalidatereturn[2]; Change of place
Optional MSG read from the server
var msg = json.jsonvalidatereturn[1]; Change of place
if (!status) {
Houston, we have a problem--show a red hint
Options.ajaxvalidcache[errorfieldid] = false;
Options.iserror = true;

5.4 Fourth step, the custom rule in the language file, the official language pack has the Chinese language file call Jquery.validationengine-zh_cn.js, here I add a "ajaxusers" rule.
Copy Code code as follows:

---CUSTOM RULES--those are specific to the demos, they can is removed or changed to your likings
"Ajaxusers": {
"url": "Ajaxbackstage/ajaxvalidation.ashx",//"Validate.action", "Validate.action" Ajax authentication username, The following parameters will be post: Validateerror Ajaxuser;validateid user;validatevalue CCCC
"Alerttextok": "* account number can be used.",
"Alerttextload": "* check, please later ...",
"Alerttext": "* account cannot be used."
},
"Ajaxusercall": {
"url": "Ajaxvalidatefielduser",
You could want to pass extra data in the AJAX call
"Extradata": "Name=eric",
"Alerttext": "* This name has been used by others",
"Alerttextload": "* is confirming that the name is used by other people, please wait a moment. "
},

OK, try to verify whether it can be successful ...

Finally, sum up a little experience and share it. "Look for answers to questions from the nature of things!" ”。

Author: 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.