博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
MVC中的统一验证机制~续
阅读量:6605 次
发布时间:2019-06-24

本文共 5130 字,大约阅读时间需要 17 分钟。

前段时间我发表的关于MVC架构中对验证方式的设计,收到了不少朋友的留言,意思是说过于复杂,复用性不高,当然我的出发点是减少实体部门的代码量。

最近在朋友的建议下,看了另一种验证方式,事实上就是MVC实例中提供的实体属性验证方式,为每个视图加一个视图模型,对视图模型中的属性进行特性的

约束即可。具体如下:

WEB UI可能是这样

<%using (Html.BeginForm())

      {  %>
    <%=Html.LabelFor(model=>model.Name) %>
    <%=Html.TextBoxFor(model=>model.Name) %>
    <%=Html.ValidationMessageFor(model=>model.Name) %>
    <%=Html.LabelFor(model=>model.Age) %>
    <%=Html.TextBoxFor(model => model.Age)%>
    <%=Html.ValidationMessageFor(model => model.Age)%>
    <input type="submit" value="Save" />
    <%} %>

Model可能是这样

namespace Web.Models

{
    public class PersonModels
    {
        [Required("RequiredField", "Name")]
        public string Name { get; set; }
        [Range(18, int.MaxValue, "GreaterThan", "Age", 18)]
        public int Age { get; set; }
        [Range(int.MinValue, 160, "LessThan", "Weight", 160)]
        public double Weight { get; set; }
        [Required("EmailField", "Email")]
        [Email("EmailField", "Email")]
        public string Email { get; set; }
    }
}

而controller可能是这样

[HttpPost]

        public ActionResult Index(FormCollection form)
        {
            if (this.ModelState.IsValid)
            {
                // 验证通过的逻辑
                Response.Output.Write("<script>alert('验证通过');</script>");
            }
            return View();
        }

最后实体具一类可能是这样

namespace Web.Mvc.Extensions

{
    /// <summary>
    /// 通用验证基类
    /// </summary>
    public abstract class EntityValidationAttribute : ValidationAttribute
    {
        public EntityValidationAttribute(string messageId, params object[] args) :
            base(() => MessageManager.Current.GetMessage(messageId, args)) { }
        #region Protected Property
        protected Regex rLetters { get { return new Regex("[a-zA-Z]{1,}"); } }
        /// <summary>
        /// 验证数字
        /// </summary>
        protected Regex rDigit { get { return new Regex("[0-9]{1,}"); } }
        /// <summary>
        /// 验证邮编
        /// </summary>
        protected Regex rPostNumber { get { return new Regex("^[0-9]{3,14}$"); } }
        /// <summary>
        /// 验证手机
        /// </summary>
        protected Regex rMobile { get { return new Regex(@"^1[3|4|5|8][0-9]\d{8}$"); } }
        /// <summary>
        /// 验证电话
        /// </summary>
        protected Regex rTelePhone { get { return new Regex(@"^[0-9]{2,4}-\d{6,8}$"); } }
        /// <summary>
        /// 验证传真
        /// </summary>
        protected Regex rFex { get { return new Regex(@"/^[0-9]{2,4}-\d{6,8}$"); } }
        /// <summary>
        /// 验证Email
        /// </summary>
        protected Regex rEmail { get { return new Regex(@"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"); } }
        #endregion
    }
    /// <summary>
    /// 为空验证
    /// </summary>
    [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
    public class RequiredAttribute : EntityValidationAttribute
    {
        public bool AllowEmptyStrings { get; set; }
        public RequiredAttribute(string messageId, params object[] args) :
            base(messageId, args)
        { }
        public override bool IsValid(object value)
        {
            return new System.ComponentModel.DataAnnotations.RequiredAttribute { AllowEmptyStrings = this.AllowEmptyStrings }.IsValid(value);
        }
    }
    /// <summary>
    /// 范围验证
    /// </summary>
    [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
    public class RangeAttribute : EntityValidationAttribute
    {
        private System.ComponentModel.DataAnnotations.RangeAttribute innerRangeAttribute;
        public RangeAttribute(double minimum, double maximum, string messageId, params object[] args) :
            base(messageId, args)
        {
            innerRangeAttribute = new System.ComponentModel.DataAnnotations.RangeAttribute(minimum, maximum);
        }
        public RangeAttribute(int minimum, int maximum, string messageId, params object[] args) :
            base(messageId, args)
        {
            innerRangeAttribute = new System.ComponentModel.DataAnnotations.RangeAttribute(minimum, maximum);
        }
        public RangeAttribute(Type type, string minimum, string maximum, string messageId, params object[] args) :
            base(messageId, args)
        {
            innerRangeAttribute = new System.ComponentModel.DataAnnotations.RangeAttribute(type, minimum, maximum);
        }
        public override bool IsValid(object value)
        {
            return innerRangeAttribute.IsValid(value);
        }
    }
    /// <summary>
    /// Email验证
    /// </summary>
    [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
    public class EmailAttribute : EntityValidationAttribute
    {
        public EmailAttribute(string messageId, params object[] args) :
            base(messageId, args)
        { }
        public override bool IsValid(object value)
        {
            if (value == null)
                return false;
            else
                return rEmail.IsMatch(value.ToString());
        }
    }
    /// <summary>
    /// 消息类
    /// </summary>
    public class MessageManager
    {
        static Dictionary<string, string> messages = new Dictionary<string, string>();
        static MessageManager()
        {
            messages.Add("RequiredField", "这个 \"{0}\"字段是必填的!");
            messages.Add("GreaterThan", "这个 \"{0}\" 字段的值必须大于 \"{1}\"!");
            messages.Add("LessThan", "这个 \"{0}\" 字段的值必须小于 \"{1}\"!");
            messages.Add("EmailField", "这个 \"{0}\" 字段不是有效的Email地址!");
        }
        /// <summary>
        /// 得到验证异常的消息集合
        /// 对外公开
        /// </summary>
        /// <param name="messageId">异常消息ID</param>
        /// <param name="args">消息参数集合</param>
        /// <returns></returns>
        public string GetMessage(string messageId, params object[] args)
        {
            return string.Format(CultureInfo.CurrentCulture, messages[messageId], args);
        }
        /// <summary>
        /// 本类的实例对象
        /// </summary>
        public static MessageManager Current = new MessageManager();
    }
}

转载地址:http://otfso.baihongyu.com/

你可能感兴趣的文章
GETTING UP AND RUNNING WITH NODE.JS, EXPRESS, JADE, AND MONGODB
查看>>
求二叉树第K层节点的个数
查看>>
关于cocos2d-x面试的问题
查看>>
MySQLs数据库建外键时自动跑到缩影处,真奇怪
查看>>
static关键字
查看>>
js 合并多个对象 Object.assign
查看>>
Java 反射机制
查看>>
Unity 碰撞检测中碰撞器与触发器的区别
查看>>
Elasticsearch配置文件说明
查看>>
路由表的构成
查看>>
初识java
查看>>
temporary Object and destructor
查看>>
xcode - 移动手势
查看>>
细说浏览器特性检测(1)-jQuery1.4添加部分
查看>>
古中国数学家的计算力真是惊人
查看>>
Java基础-算术运算符(Arithmetic Operators)
查看>>
XML 基础
查看>>
C#编程(四十七)----------集合接口和类型
查看>>
【转】关于大型网站技术演进的思考(十二)--网站静态化处理—缓存(4)
查看>>
积跬步,聚小流------Bootstrap学习记录(1)
查看>>