ASP. net mvc and WebForm easily implement dual-validation of the front-end and back-end jquery. validate + ValidationSugar,

Source: Internet
Author: User

ASP. net mvc and WebForm easily implement dual-validation of the front-end and back-end jquery. validate + ValidationSugar,

 

Improvement of the last Deficiency

 

The previous post may cause many misunderstandings. Therefore, I have improved the DEMO in two versions: ASP. NET WEBFROM and ASP. NET MVC]

Some bugs have been modified and some details have been modified.

Someone said in the previous post that reading response. write is uncomfortable, so I wrote an example based on Asynchronous submission.

 

 

 

Features

ValidationSugar. cs is responsible for backend verification and binding the validation attribute of the front-end form Element

ValidationSugar. js encapsulates jquery. validate for front-end verification.

 

Note: ValidationSugar. cs

Supported now

1. HTML5 default verification function

2. jquery. validate

3. Verification of HTML5 + CSS3 in webform demo1

Other front-end verification can be expanded by yourself

 

 

Background:

 

 

Front-end:

1. Reference four scripts first:

    <script src="/Content/jquery-validation-1.13.1/lib/jquery-1.9.1.js" type="text/javascript"></script>    <script src="/Content/jquery-validation-1.13.1/dist/jquery.validate.js"></script>    <script src="/Content/ValidationSugar.js" type="text/javascript"></script>    <script src="/Content/jquery-validation-1.13.1/lib/jquery.form.js" type="text/javascript"></script>

 

  

2. script call is so simple

<Script type = "text/javascript"> $ (function () {var factory = new validateFactory ($ ("form"); factory. init (); $ ("# btnSubmit "). click (function () {// asynchronous factory. ajaxSubmit (function () {$ ("form "). ajaxSubmit ({type: "post", url: "/home/post", dataType: "json", success: function (msg) {alert (msg. message) }})}) ;}); </script>

  

3. HTML code

 

DEMO:Http://git.oschina.net/sunkaixuan/ValidationSuarMVC (includes WEBFROM)

Because I wrote it for two days, I will inevitably consider it. I will update it slowly in my future work. Thank you for watching it.

 

 

 

Encapsulation code:

 

ValidationSugar.cs:
Using System; using System. collections. generic; using System. linq; using System. text; using System. text. regularExpressions; namespace SyntacticSugar {// <summary> /// ** Description: it is convenient to implement dual-end and front-end verification. Based on jquery /// ** Creation Time: // ** modification time:-// ** Author: sunkaixuan // ** instructions for use: http://www.cnblogs.com/sunkaixuan/p/4550580.html /// ** Git: http://git.oschina.net/sunkaixuan/SyntacticSugar /// </Summary> public class ValidationSugar {private static List <ValidationOption> ValidationOptionList = new List <ValidationOption> (); /// <summary> /// foreground injection /// </summary> /// <param name = "pageKey"> </param> /// <param name = "itemList"> </param> public static string GetInitScript (string pageKey, list <OptionItem> itemList) {// After initialization, if (ValidationOptionList. any (it => it. pageKey = pageKey) {Val IdationOptionList. removeAll (it => it. pageKey = pageKey);} ValidationOption option = new ValidationOption (); string uk = Guid. newGuid (). toString (). replace ("-", ""); // unique function name string script = @ "<script> var bindValidation {1} = function (name, params) {var selectorObj = $ ("" [name = '"" + name + ""'] ""). last (); selectorObj. after ("" <span class = \ "" form_hint \ ""> "" + params. tip + "" </span> ""); if (params. pattern! = Null) selectorObj. attr ("" pattern "", params. pattern); if (params. placeholder! = Null) selectorObj. attr ("" placeholder "", params. placeholder); if (params. isRequired = true) selectorObj. attr ("" required "", params. isRequired) ;}}{ 0} </script> "; StringBuilder itemsCode = new StringBuilder (); foreach (var item in itemList) {switch (item. type) {case OptionItemType. mail: item. pattern = @ "^ [\ w-] + (\\. [\ w-] +) * @ [\ w-] + (\\. [\ w-] +) + $ "; break; case OptionItemType. int: item. pattern = @ "^ \ d {1, 11} $ "; break; case OptionItemType. double: item. pattern = @ "^ \ d {1, 11} $"; break; case OptionItemType. idCard: item. pattern = @ "^ (\ d {15 }$ | ^ \ d {18 }$ | ^ \ d {17} (\ d | X | x )) $ "; break; case OptionItemType. date: item. pattern = @ "^ (1 [8-9] \ d {2}) | ([2-9] \ d {3 })) ([-\/]) (10 | 12 | 0? [13578]) ([-\/]) (3 [01] | [12] [0-9] | 0? [1-9]) $) | (^ (1 [8-9] \ d {2 }) | ([2-9] \ d {3}) ([-\/]) (11 | 0? [469]) ([-\/]) (30 | [12] [0-9] | 0? [1-9]) $) | (^ (1 [8-9] \ d {2 }) | ([2-9] \ d {3}) ([-\/]) (0? 2) ([-\/]) (2 [0-8] | 1 [0-9] | 0? [1-9]) $) | (^ ([2468] [048] 00) ([-\/]) (0? 2) ([-\/]) (29) $) | (^ ([3579] [26] 00) ([-\/]) (0? 2) ([-\/]) (29) $) | (^ ([1] [89] [0] [48]) ([-\/]) (0? 2) ([-\/]) (29) $) | (^ ([2-9] [0-9] [0] [48]) ([-\/]) (0? 2) ([-\/]) (29) $) | (^ ([1] [89] [2468] [048]) ([-\/]) (0? 2) ([-\/]) (29) $) | (^ ([2-9] [0-9] [2468] [048]) ([-\/]) (0? 2) ([-\/]) (29) $) | (^ ([1] [89] [13579] [26]) ([-\/]) (0? 2) ([-\/]) (29) $) | (^ ([2-9] [0-9] [13579] [26]) ([-\/]) (0? 2) ([-\/]) (29) | (0 [13578]) | ([13578]) | (1 [02]) [\-\/\ s]? (0 [1-9]) | ([1-9]) | ([1-2] [0-9]) | (3 [01]) | ([469]) | (11) [\-\/\ s]? (0 [1-9]) | ([1-9]) | ([1-2] [0-9]) | (30 ))) | (02 | 2) [\-\/\ s]? (0 [1-9]) | ([1-9]) | ([1-2] [0-9]) [\-\/\ s]? \ D {4}) (\ s (0 [1-9]) | ([1-9]) | (1 [0-2]) \: ([0-5] [0-9]) (\ s) | (\: ([0-5] [0-9]) \ s) ([AM | PM | am | pm] {2, 2 })))? $ "; Break; case OptionItemType. mobile: item. pattern = @ "^ [0-9] {11} $"; break; case OptionItemType. telephone: item. pattern = @ "^ (\ d {3, 4} \) | \ d {3, 4}-| \ s )? \ D {8} $ "; break; case OptionItemType. Fax: item. Pattern = @" ^ [+] {0, 1} (\ d) {1, 3} []? ([-]? (\ D) | []) {1, 12}) + $ "; break; case OptionItemType. regex: item. pattern = item. pattern. replace (@ "\", @ "\"); break;} itemsCode. appendFormat ("bindValidation {0} ('{1}', {tip: '{2}', pattern: '{3}', placeholder: '{4 }', isRequired: {5 }}) ", uk, item. formFiledName, item. tip, item. pattern, item. placeholder, item. isRequired? "True": "false"); itemsCode. appendLine ();} option. script = string. format (script, itemsCode. toString (), uk); script = null; itemsCode. clear (); option. pageKey = pageKey; option. itemList = itemList; ValidationOptionList. add (option); return (option. script );} /// <summary> /// background verification /// </summary> /// <param name = "pageKey"> </param> /// <param name = "errorMessage"> json format </param> // <returns> </returns> Public static bool PostValidation (string pageKey, out string errorMessage) {bool isSuccess = true; errorMessage = string. Empty; if (! ValidationOptionList. any (c => c. pageKey = pageKey) {throw new ArgumentNullException ("ValidationSugar. postValidation. pageKey ");} var context = System. web. httpContext. current; var itemList = ValidationOptionList. where (c => c. pageKey = pageKey ). single (). itemList; var successItemList = itemList. where (it => (it. isRequired &&! String. IsNullOrEmpty (context. Request [it. FormFiledName]) |! It. isRequired )). where (it => {if (it. isMultiselect = true) {var errorList = context. request [it. formFiledName]. split (','). where (itit => {var isNotMatch =! Regex. isMatch (itit, it. pattern. replace (@ "\", @ "\"); return isNotMatch ;}). toList (); return errorList. count = 0;} else {return Regex. isMatch (context. request [it. formFiledName], it. pattern. replace (@"\\",@"\"));}}). toList (); isSuccess = (successItemList. count = itemList. count); if (! IsSuccess) {errorMessage = new System. web. script. serialization. javaScriptSerializer (). serialize (itemList);} return isSuccess;} private class ValidationOption {public string PageKey {get; set;} public string Script {get; set ;} public List <OptionItem> ItemList {get; set ;}} public enum OptionItemType {Mail = 0, Int = 2, Double = 3, IdCard = 4, Date = 5, /// <summary> /// mobile phone /// </summary> Mobile = 6, /// <summary> // landline // </summary> Telephone = 7, Fax = 8, /// <summary> /// no suitable, please use regular expression verification /// </summary> Regex = 1000} /// <summary> /// verification options /// </summary> public class OptionItem {/// <summary> /// verification Type /// </summary> public OptionItemType {get; set ;}//< summary> /// regular // </summary> public string Pattern {get; set ;} /// <summary> /// required? /// </summary> public bool IsRequired {get; set;} // <summary> // form field name (name or id) /// </summary> public string FormFiledName {get; set ;} /// <summary> /// watermark /// </summary> public string Placeholder {get; set ;} /// <summary> /// reminder /// </summary> public string Tip {get; set ;}/// <summary> /// is multiple selections selected? Default Value: false /// </summary> public bool IsMultiselect {get; set ;}}}}

 

 

validationSagur.js:

 

// Validate Based on validate // Author: sunkaixuan // time: 2015-6-5var validateFactory = function (form) {this. init = function () {addMethod (); bind ();} this. submit = function () {if (form. data ("validateFactory") {form. data ("validateFactory "). form () ;}} this. ajaxSubmit = function (rollback) {if (form. data ("validateFactory") {if (form. valid () {if (rollback! = Null) {rollback () ;}}} function addMethod () {form. find ("[pattern]"). each (function () {var th = $ (this); var pattern = GetPattern (th); var methodName = GetMdthodName (th); $. validator. addMethod (methodName, function (value, element, params) {return this. optional (element) | new RegExp (pattern ). test (value) ;}, GetTip (th) ;}function bind () {var rules ={}; var messages ={}; form. find (" [Pattern] "). each (function () {var th = $ (this); var methodName = GetMdthodName (th); var name = GetName (th); rules [name] = {}; rules [name] [methodName] = true; if (GetIsRequired (th) {rules [name]. required = true; messages [name] ={}; messages [name]. required = "cannot be blank! ";}}); Var v = form. validate ({onfocusout: function (element) {$ (element ). valid () ;}, onkeyup: function (element) {$ (element ). valid () ;}, rules: rules, messages: messages, debug: false, errorPlacement: function (error, element) {if (element. is (": radio,: checkbox") {element. parent (). append (error);} else {element. after (error) ;}}}); form. data ("validateFactory", v);} function GetMdthodName (ele) {return ele. attr ("name") + "ValidateMethod";} function GetName (ele) {return ele. attr ("name");} function GetPattern (ele) {return ele. attr ("pattern");} function GetTip (ele) {return ele. next (). text ();} function GetIsRequired (ele) {if (ele. attr ("required") {return true;} else {return false ;}}};

  

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.