/// <summary> /// 根据传入属性字段决定是否需要必填字段 /// </summary> [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true, Inherited = false)] public class CustomRequiredMinValueCompareAttribute : ValidationAttribute { private MinValueCompareAttribute innerAttribute; private string DependentProperty { get; set; } private object TargetValue { get; set; } public CustomRequiredMinValueCompareAttribute(string dependentProperty, object targetValue, int minimum) { this.DependentProperty = dependentProperty; this.TargetValue = targetValue; innerAttribute = new MinValueCompareAttribute(minimum); } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { var field = validationContext.ObjectInstance.GetType().GetProperty(DependentProperty); if (field != null) { var dependentValue = field.GetValue(validationContext.ObjectInstance, null); if (Object.Equals(dependentValue, TargetValue)) { if (!innerAttribute.IsValid(value)) return new ValidationResult(ErrorMessage, new List<string>() { validationContext.MemberName }); } } return ValidationResult.Success; } }
以上是匹配最小值
/// <summary> /// 根据传入属性字段决定是否需要必填字段 /// </summary> [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true, Inherited = false)] public class CustomRequiredValidationAttribute : ValidationAttribute { private RequiredAttribute innerAttribute = new RequiredAttribute(); private string DependentProperty { get; set; } private object TargetValue { get; set; } public CustomRequiredValidationAttribute(string dependentProperty, object targetValue) { this.DependentProperty = dependentProperty; this.TargetValue = targetValue; } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { var field = validationContext.ObjectInstance.GetType().GetProperty(DependentProperty); if (field != null) { var dependentValue = field.GetValue(validationContext.ObjectInstance, null); if (Object.Equals(dependentValue, TargetValue)) { if (!innerAttribute.IsValid(value)) return new ValidationResult(ErrorMessage, new List<string>() { validationContext.MemberName }); } } return ValidationResult.Success; } }
匹配必填
使用:
public bool IsVal { get; set; } = false; [CustomRequiredMinValueCompare("IsVal", true, 0, ErrorMessage = "IntValue不能为空!")] public int IntValue { get; set; } [CustomRequiredValidation("IsVal", true, ErrorMessage = "StringValue不能为空!")] public string StringValue { get; set; }
标签:set,必填,get,--,private,field,一字段,public,validationContext From: https://www.cnblogs.com/X-Q-X/p/16744147.html