RequiredIf带枚举的数据注释

本文关键字:数据 注释 枚举 RequiredIf | 更新日期: 2023-09-27 18:10:58

我已经创建了一个像这样的自定义RequiredIf验证器:

public class RequiredIfValidator : ValidationAttribute, IClientValidatable
{
    RequiredAttribute _innerAttribute = new RequiredAttribute();
    public string _dependentProperty { get; set; }
    public object _targetValue { get; set; }
    public RequiredIfValidator(string dependentProperty, object targetValue)
    {
        this._dependentProperty = dependentProperty;
        this._targetValue = targetValue;
    }
    public override string FormatErrorMessage(string name)
    {
        return string.Format(CultureInfo.CurrentCulture, ErrorMessageString, name, _dependentProperty);
    }
    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 ((dependentValue == null && _targetValue == null) ||(dependentValue.Equals(_targetValue)))
            {
                if (!_innerAttribute.IsValid(value))
                {
                    return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
                }
            }
        }
        return ValidationResult.Success;
    }
    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule();
        rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
        rule.ValidationType = "requiredif";
        rule.ValidationParameters["dependentproperty"] = _dependentProperty;
        rule.ValidationParameters["targetvalue"] = _targetValue;
        yield return rule;
    }
}

我有一个包含各种测试类型的enum,像这样:

public enum TestTypes 
{
    Hair = 1,
    Urine = 2
}

我的ViewModel有一些像这样的属性:

public class TestViewModel
{
    public TestTypes TestTypeId {get; set;}
    [RequiredIfValidator("TestTypeId", TestTypes.Hair)]
    public string HairSpecimenId {get; set;}
}

我的自定义RequiredIfValidator在这个场景中不起作用。是因为枚举数据类型吗?使用枚举

RequiredIf带枚举的数据注释

实现此目的的任何方法

您在IsValid()中的逻辑似乎不正确。应该是

protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
  if (value == null)
  {
    var otherProperty = validationContext.ObjectInstance.GetType().GetProperty(_dependentProperty);
    var otherPropertyValue = otherProperty.GetValue(validationContext.ObjectInstance, null);
    if (otherPropertyValue != null && otherPropertyValue.Equals(_targetValue ))
    {
      return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
    }
  }
  return ValidationResult.Success;
}