创建一个类,引用 using System.ComponentModel.DataAnnotations;
////// 自定义模型验证 /// public class TestValidator { ////// 年龄大小验证 /// /// ///public static ValidationResult TestAge(int age) { if (age < 18) { return new ValidationResult("未满18岁"); } else { return ValidationResult.Success; } } /// /// 手机号码格式验证 /// /// ///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(类名),“方法名”)]



