码迷,mamicode.com
首页 > 其他好文 > 详细

前端和后端的双重验证

时间:2015-06-06 13:22:46      阅读:335      评论:0      收藏:0      [点我收藏+]

标签:

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个脚本:

1
2
3
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、脚本调用就这么简单

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<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 =>
                    {
                        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>
            /// 移动电话
            /// </summary>
            Mobile = 6,
            /// <summary>
            /// 座机
            /// </summary>
            Telephone = 7,
            Fax = 8,
            /// <summary>
            /// 没有合适的,请使用正则验证
            /// </summary>
            Regex = 1000

        }
        /// <summary>
        /// 验证选项
        /// </summary>
        public class OptionItem
        {
            /// <summary>
            /// 验证类型
            /// </summary>
            public OptionItemType Type { get; set; }
            /// <summary>
            /// 正则
            /// </summary>
            public string Pattern { get; set; }
            /// <summary>
            /// 是否必填
            /// </summary>
            public bool IsRequired { get; set; }
            /// <summary>
            /// 表单字段名(name或者id)
            /// </summary>
            public string FormFiledName { get; set; }
            /// <summary>
            /// 水印
            /// </summary>
            public string Placeholder { get; set; }
            /// <summary>
            /// 提醒
            /// </summary>
            public string Tip { get; set; }
            /// <summary>
            /// 是多选吗? 默认false
            /// </summary>
            public bool IsMultiselect { get; set; }

        }
    }
}
技术分享

 

 

1
validationSagur.js:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
//基于validate验证
//作者:sunkaixuan
//时间:2015-6-5
var 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 = "不能为空!";
            }
 
 
        });
        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;
        }
    }
};

  

 
分类: Git

前端和后端的双重验证

标签:

原文地址:http://www.cnblogs.com/Leo_wl/p/4556358.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!