自定义模型验证

创建一个类,引用 using System.ComponentModel.DataAnnotations;

    /// <summary>
    /// 自定义模型验证
    /// </summary>
    public class TestValidator
    {
        /// <summary>
        /// 年龄大小验证
        /// </summary>
        /// <param name="age"></param>
        /// <returns></returns>
        public static ValidationResult TestAge(int age)
        {
            if (age < 18)
            {
                return new ValidationResult("未满18岁");
            }
            else
            {
                return ValidationResult.Success;
            }
        }

        /// <summary>
        /// 手机号码格式验证
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        public static ValidationResult TestPhone(string phone)
        {
            if ((phone.StartsWith("13") || phone.StartsWith("15") || phone.StartsWith("17")) && phone.Length == 11)
            {
                return ValidationResult.Success;
            }
            else
            {
                return new ValidationResult("手机号码格式错误");
            }
        }
    }

需要验证的模型类

public class UserInfoToModel
    {
        [Required(ErrorMessage = "账号不能为空")]
        public string UserName { get; set; }

        [Required(ErrorMessage = "密码不能为空"), MinLength(6, ErrorMessage = "密码不能小于6个字符")]
        public string UserPwd { get; set; }

        [CustomValidation(typeof(TestValidator), "TestAge")]
        public int UserAge { get; set; }

        [CustomValidation(typeof(TsetValidator), "TestPhone")]
        public string UserPhone { get; set; }
    }

[CustomValidation(typeof(类名),“方法名”)]

posted @ 2021-10-11 10:34  kele-cc  阅读(95)  评论(0)    收藏  举报