2

我有一个 custom ValidationAttribute,但是我只想在选中 CheckBox 时验证这个属性。

我已经让我的类继承IValidationObject并使用该Validate方法来执行任何自定义验证,但是我可以在ValidationAttribute这里使用自定义而不是复制代码吗?如果是这样,怎么办?

public class MyClass : IValidatableObject
{
    public bool IsReminderChecked { get; set; }
    public bool EmailAddress { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (IsReminderChecked)
        {
            // How can I validate the EmailAddress field using
            // the Custom Validation Attribute found below?
        }
    }
}


// Custom Validation Attribute - used in more than one place
public class EmailValidationAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        var email = value as string;

        if (string.IsNullOrEmpty(email))
            return false;

        try
        {
            var testEmail = new MailAddress(email).Address;
        }
        catch (FormatException)
        {
            return false;
        }

        return true;
    }
}
4

1 回答 1

6

可以根据另一个属性的值来验证一个属性,但是要确保验证引擎按您期望的方式工作,需要跳过一些环节。Simon Ince 的RequiredIfAttributeValidateEmailIfAttribute有一个很好的方法,只需将您的电子邮件验证逻辑添加到该方法即可轻松将其修改为IsValid

例如,您可以拥有基本验证属性,就像现在一样:

public class ValidateEmailAttribute : ValidationAttribute
{
  ...
}

然后使用因斯的方法定义条件版本:

public class ValidateEmailIfAttribute : ValidationAttribute, IClientValidatable
{
  private ValidateEmailAttribute _innerAttribute = new ValidateEmailAttribute();

  public string DependentProperty { get; set; }
  public object TargetValue { get; set; }

  public ValidateEmailIfAttribute(string dependentProperty, object targetValue)
  {
    this.DependentProperty = dependentProperty;
    this.TargetValue = targetValue;
  }

  protected override ValidationResult IsValid(object value, ValidationContext validationContext)
  {
    // get a reference to the property this validation depends upon
    var containerType = validationContext.ObjectInstance.GetType();
    var field = containerType.GetProperty(this.DependentProperty);

    if (field != null)
    {
      // get the value of the dependent property
      var dependentvalue = field.GetValue(validationContext.ObjectInstance, null);

      // compare the value against the target value
      if ((dependentvalue == null && this.TargetValue == null) ||
          (dependentvalue != null && dependentvalue.Equals(this.TargetValue)))
      {
        // match => means we should try validating this field
        if (!_innerAttribute.IsValid(value))
          // validation failed - return an error
          return new ValidationResult(this.ErrorMessage, new[] { validationContext.MemberName });
      }
    }

    return ValidationResult.Success;
  }

  // Client-side validation code omitted for brevity
}

然后你可以有类似的东西:

[ValidateEmailIf("IsReminderChecked", true)]
public bool EmailAddress { get; set; }
于 2012-06-20T15:35:20.043 回答