向MVC的Model中添加验证

ASP.NET MVC 的核心设计原则之一是DRY(Don’t Repeat Yourself)——”不要重复自己”。在Model中添加验证可以省去我们在服务器端对数据的进行的繁琐验证操作。用好验证特性可以使代码更简洁,易扩展,易维护。

向MVC的Model中添加验证特性:

MVC的服务端验证流程是这样的:
客户端请求—>Route解析—> model绑定—> 数据验证.

命名空间:using System.ComponentModel.DataAnnotations;

举个栗子:

public class Model
{
    public int ID { get; set; }

    [StringLength(60, MinimumLength = 3)]
    public string Name { get; set; }

    [Display(Name = "Registe Date")]
    [DataType(DataType.Date)]
    public DateTime Date { get; set; }

    [RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$")] 
    [Required]
    [StringLength(30)]
    public string Genre { get; set; }

    [Range(1, 100)]
    [DataType(DataType.Currency)]
    public decimal Price { get; set; }

}

验证特性种类:

  1. [Required] : 必填项
    [Required(ErrorMessage = "请输入姓名")]

  2. [StringLength] : 限制字符串长度
    [StringLength(MaximumLength = 10 , MinimumLength = 3,ErrorMessage = "字符长度在3~10之间")]

  3. [Range] : 限制取值范围
    [Range(0, 120, ErrorMessage = "取值范围在0~120之间")]

  4. [RegularExpression] : 匹配符合某个正则表达式
    [RegularExpression(@"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$", ErrorMessage = "请输入正确的Email")]

  5. Compare :判等比较
    [Compare("Pwd", ErrorMessage = "两次密码不一致")]

  6. Remote : Ajax远程验证,返回值是bool类型 true表示验证通过

    //ValideUser为行为Action,Validate为控制器Controller
    [Remote("ValideUser", "Validate", HttpMethod = "post", ErrorMessage = "用户名已存在")]
    public string UserName { get; set; }  
    
    public IActionResult ValideUser()  
    {   
    if(//条件...)  
    {  
    return Json(true,JsonRequestBehavior.AllowGet);  
    }  
    else  
    return Json(false,JsonRequestBehavior.AllowGet);  
    }  
  7. OutputCache :设置页面缓存

    //Duration单位:秒
    [OutputCache(Duration=20)] 
    public IActionResult Index()  
    {  
     //......
    }  
  8. 自定义正则验证特性

    public class EmailValid : RegularExpressionAttribute  
    {  
        public EmailValid ()  
            :base(@"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$")  
        {  
        }  
    }  
  9. 扩展验证特性

    实现服务器+客户端验证:继承ValidationAttribute ,实现IClientValidatable 接口

    public class CheckAttribute : ValidationAttribute ,IClientValidatable 
    { 
       //重写IsValid验证方法
       public override bool IsValid(object value) 
       { 
           if (value == null) return false; 
           if (value.GetType() != typeof(bool)) 
               throw new InvalidOperationException("只能用于Bool属性"); 
           return (bool)value; 
       }
    
       //重写 FormatErrorMessage错误消息提示方法
       public override string FormatErrorMessage(string name) 
       { 
           return name==null?"请仔细阅读相关协议":name; 
       }
    
       //实现GetClientValidationRules方法
       public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) 
      { 
        yield return new ModelClientValidationRule 
        { 
            ErrorMessage = String.IsNullOrEmpty(ErrorMessage) ? FormatErrorMessage(metadata.DisplayName) : ErrorMessage, 
            ValidationType = "checkfocus" 
        }; 
      }     
    }

    通过实现IClientValidatable接口,使程序在生成html代码时候,为相应的input添加上了额外的验证规则,但是这些规则在客户端上,还没有方法来启动验证。
    添加JQuery代码:

    //添加ValidationType 
    <script type="text/javascript"> 
      jQuery.validator.addMethod("checkfocus", function(value, element, param) { 
          return element.checked; 
      }); 
      jQuery.validator.unobtrusive.adapters.addBool("checkfocus"); 
    </script>

数据格式化特性

  1. DisplayName:设定字段显示的名字
    [DisplayName("User Name")]

  2. DataType:用于视图引擎对数据进行格式化

    [DataType(DataType.EmailAddress)] 邮箱
    
    [DataType(DataType.CreditCard)]​​   信用卡
    
    [DataType(DataType.Currency)]​   货币
    
    [DataType(DataType.Date)]​   日期
    
    [DataType(DataType.DateTime)]​   日期时间
    
    [DataType(DataType.Html)]HTML文件
    
    [DataType(DataType.ImageUrl)]​   图片的URL
    
    [DataType(DataType.MultilineText)]​   多行文本
    
    [DataType(DataType.Password)]​   密码值
    
    [DataType(DataType.PhoneNumber)]    电话号码值
    
    [DataType(DataType.PostalCode)]​​   邮政代码
    
    [DataType(DataType.Time)]​   时间
    
    [DataType(DataType.Upload)]​  文件上载数据类型
    
    [DataType(DataType.Url)]URL
  3. ReadOnly:指定该特性所绑定到的属性是只读属性
    [ReadOnly(true)]

总结

扩展验证特性的使用:
1. 服务端创建验证属性类并继承ValidationAttribute, 实现服务端的验证。
2. 验证属性类实现IClientValidatable接口,为生成的input标签添加客户端验证规则,同时扩展客户端验证方法。

附加内容:模型绑定

MVC 包含几种与默认绑定源不同行为的 Attribute 。

[BindRequired]:表示如果这个绑定不能发生,将添加一个模型状态错误(Model State Error)。

[BindNever]:表示这个参数不进行绑定。

[FromServices]:表示使用 dependency injection 通过服务来绑定参数。

[FromBody]:从 HTTP 请求的 Body 中绑定数据。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章