RequiredIf数据注释与枚举

时间:2015-09-02 05:47:03

标签: c# asp.net-mvc data-annotations

我已经创建了一个自定义的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在此scinario中无效。是因为枚举数据类型?用枚举

实现这一目标的任何方法

1 个答案:

答案 0 :(得分:1)

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

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