美文网首页asp.net mvc
asp.net mvc Model Valid

asp.net mvc Model Valid

作者: 落地成佛 | 来源:发表于2017-12-14 14:58 被阅读12次

    1、自带验证

    • 非空
    [Require]
    
    • 字符串长度
    //长度6-100
     [StringLength(100, MinimumLength = 6)]
    
    • 数据类型
    [DataType(DataType.Password)]
    
    • 正则表达式
     [RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9._]+\.[A-Za-z]{2,4}")]
    
    • 相同验证
    public string Password { get; set; }
    [Compare("Password", ErrorMessage = "密码和确认密码不匹配。")]
    public string ConfirmPassword { get; set; }
    
    • 数值范围
     [Range(13, 18)]
    
    • 远程验证
            //Model
            [Required]
            [Display(Name = "用户名")]
            [Remote("CheckUserName","Account")]
            public string UserName { get; set; }
            //control
            public JsonResult CheckUserName(string userName)
            {
                var result = userName == "admin";
                return Json(result, JsonRequestBehavior.AllowGet);
            }
    

    2、自定义验证

    2.1 继承ValidationAttribute(全局都可以使用)

    public class MyMaxLengthAttribute : ValidationAttribute
        {
            private readonly int MaxLength;
     
            public MyMaxLengthAttribute(int maxLength)
            {
                MaxLength = maxLength;
            }
     
            protected override ValidationResult IsValid(object value, ValidationContext validationContext)
            {
                string content = value.ToString();
                if (content.Length > MaxLength)
                {
                    return new ValidationResult("输入的字符太多了!^_^");
                }
                return ValidationResult.Success;
                //return base.IsValid(value, validationContext);
            }
    

    2.2 Model类实现接口IValidatableObject(限于该Model类使用,但可以很方便地对该Model的所以属性进行验证)

       public IEnumerable<ValidationResult> Validate(ValidationContext validationContent)
            {
                if (Password != ConfirmPassword)
                {
                    yield return new ValidationResult("两次输入的密码不同!", new[] { "Password" });
                }
            }
    

    相关文章

      网友评论

        本文标题:asp.net mvc Model Valid

        本文链接:https://www.haomeiwen.com/subject/zrzhwxtx.html