MVC中的统一验证机制~续

前段时间我发表的关于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();
    }
}

posted @ 2011-12-20 23:12  张占岭  阅读(1044)  评论(0编辑  收藏  举报