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();
??? }
}
本文轉自博客園張占嶺(倉儲大叔)的博客,原文鏈接:MVC中的統一驗證機制~續,如需轉載請自行聯系原博主。
總結
以上是生活随笔為你收集整理的MVC中的统一验证机制~续的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 几分钟了解阿里云云服务器ECS
- 下一篇: NLB网路负载均衡管理器详解