asp .net core 自定义 模型验证
顺序: 请求 => 路由 => 模型绑定 => 模型验证 => 本身验证 => action => 相应
一、共用自定义模型验证
继承:ValidationAttribute
实现:override IsValid() 两个参数
1、单属性
using System.ComponentModel.DataAnnotations; namespace FirstApp.Validator { public class MiniBirthYearAttribute : ValidationAttribute { public MiniBirthYearAttribute(int targetYear) { TargetYear = targetYear; } public int TargetYear { get; set; } protected override ValidationResult? IsValid(object? value, ValidationContext validationContext) { if (value == null) return null; DateTime dateTime = Convert.ToDateTime(value); if (dateTime.Year > TargetYear) { return new ValidationResult(string.Format(ErrorMessage??"Birth year error", validationContext.DisplayName, TargetYear)); } return ValidationResult.Success; } } }
2、多属性(比较)
using System.ComponentModel.DataAnnotations; using System.Data; using System.Reflection; namespace FirstApp.Validator { public class CompareDateTimeAttribute : ValidationAttribute { public string OtherProperty { get; set; } public string ErrMsg { get; } = "{0} Compare {1} dateTime error"; public CompareDateTimeAttribute(string otherProperty) { OtherProperty = otherProperty; } protected override ValidationResult? IsValid(object? value, ValidationContext validationContext) { if (value == null) return null; DateTime source = Convert.ToDateTime(value); PropertyInfo? propertyInfo = validationContext.ObjectType.GetProperty(OtherProperty); if (propertyInfo == null) return null; DateTime target = Convert.ToDateTime(propertyInfo.GetValue(validationContext.ObjectInstance)); if (target > source) { return new ValidationResult(string.Format(ErrorMessage ?? ErrMsg, validationContext.DisplayName, GetDisplayNameForProperty(propertyInfo) ?? OtherProperty)); } return ValidationResult.Success; } private string? GetDisplayNameForProperty(PropertyInfo property) { IEnumerable<Attribute> attributes = CustomAttributeExtensions.GetCustomAttributes(property, true); foreach (Attribute attribute in attributes) { if (attribute is DisplayAttribute display) { return display.GetName(); } } return OtherProperty; } } }
二、模型类自身自定义模型验证
模型类继承:IValidatableObject
实现方法:返回值是可枚举类型,用yield return
using FirstApp.Validator; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ModelBinding.Validation; using System.ComponentModel.DataAnnotations; namespace FirstApp.Models { public class Person : IValidatableObject { [Display(Name = "姓名")] [Required(ErrorMessage = "{0}不能为空")] [StringLength(6, MinimumLength = 2, ErrorMessage = "{0}的最小长度为{2},最大长度为{1}")] public string? Name { get; set; } [Display(Name="年龄")] [Range(0, 110, ErrorMessage = "{0}的最小值={1},最大值={2}")] public int? Age { get; set; } [Display(Name="邮箱地址")] [EmailAddress(ErrorMessage = "{0}格式错误")] [ValidateNever] public string? Email { get; set; } [Display(Name = "手机")] [RegularExpression(@"^\d{11}$", ErrorMessage = "{0}格式错误")] public string? Phone { get; set; } [Display(Name="密码")] public string? Password { get; set; } [Display(Name="确认密码")] [Compare("Password", ErrorMessage = "{0}和{1}不一样")] public string? ConfirmPassword { get; set; } [Display(Name="出生日期")] [MiniBirthYear(2010, ErrorMessage = "{0}小于{1}")] public DateTime? Birth { get; set; } [Display(Name="开始日期")] public DateTime? FromDate { get; set; } [Display(Name = "目标日期")] [CompareDateTime("FromDate", ErrorMessage = "{0}不能小于{1}")] public DateTime? ToDate { get; set; } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { if (Age.HasValue == false && Birth.HasValue == false) { yield return new ValidationResult("年龄或出生日期最少有一样", [nameof(Age), nameof(Birth)]); } } } }

浙公网安备 33010602011771号