·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> 网站建设开发 >> ASP.NET网站开发 >> ASP.NET MVC和WebForm 轻松实现前端和后端的双重验证 jquery.validate+ValidationSugar
上次不足的改进
可能上一个贴子给大家带来很多误解,所以我这次把DEMO完善了两个版本 【ASP.NET WEBFROM】和【 ASP.NET MVC】
修改了一些BUG,并且修改了一些细了
在上个贴子里有人说,看了response.write就全身不舒服,所以也就写了基于异步提交的例子
功能介绍
ValidationSugar.cs 负责后台验证和前端 form 元素的 验证 属性绑定
ValidationSugar.js 对jquery.validate在进行了一个封装来负责前端的验证
注意:ValidationSugar.cs
现在可以支持
1、HTML5默认验证功能
2、jquery.validate
3、webform demo1里面的一个HTML5+CSS3的验证
其它的前端验证可以自已去扩展
后台:
前台:
1、先引用4个脚本:
<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 type="text/javascript"> $(function () { var factory = new validateFactory($("form")); factory.init(); $("#btnSubmit").click(function () { //异步方式 factory.AjaxSubmit(function () { $("form").ajaxSubmit({ type: "post", url: "/home/post", dataType:"json", success: function (msg) { alert(msg.Message) } }) }); }); }); </script>
3、HTML代码
DEMO下载地址:http://git.oschina.net/sunkaixuan/ValidationSuarMVC (包含WEBFROM)
因为才写了2天难免会有没有考虑到的地方,我在以后工作中慢慢更新的,谢谢观看。
封装代码:
ValidationSugar.cs:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Text.RegularExPRessions;namespace SyntacticSugar{ /// <summary> /// ** 描述:可以方便实现前后端双验证,基于jquery /// ** 创始时间:2015-6-4 /// ** 修改时间:- /// ** 作者:sunkaixuan /// ** 使用说明: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> /// 前台注入 /// </summary> /// <param name="pageKey"></param> /// <param name="itemList"></param> public static string GetInitScript(string pageKey, List<OptionItem> itemList) { //初始化后不在赋值 if (ValidationOptionList.Any(it => it.PageKey == pageKey)) { ValidationOptionList.RemoveAll(it => it.PageKey == pageKey); } ValidationOption option = new ValidationOption(); string uk = Guid.NewGuid().ToString().Replace("-", "");//唯一函数名 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> /// 后台验证 /// </summary> /// <param name="pageKey"></param> /// <param name="errorMessage">json格式</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 =&