RequiredIf数据批注和枚举

问题描述 投票:-1回答:1

我已经创建了一个自定义的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;
    }
}

我有一个具有各种测试类型的枚举:

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在此场景中不起作用。是否因为枚举数据类型?用枚举实现的任何方法

c# asp.net-mvc data-annotations
1个回答
1
投票

您在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;
}
© www.soinside.com 2019 - 2024. All rights reserved.