我可以使用自定义验证属性手动验证属性吗?

Rac*_*hel 2 c# validation data-annotations

我有自定义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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Jer*_*odd 6

可以根据另一个属性的值来验证属性,但是可以通过几个环节来确保验证引擎以您期望的方式工作.Simon Ince的RequiredIfAttribute有一个很好的方法,ValidateEmailIfAttribute通过在IsValid方法中添加电子邮件验证逻辑,可以很容易地将其修改为一个.

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

public class ValidateEmailAttribute : ValidationAttribute
{
  ...
}
Run Code Online (Sandbox Code Playgroud)

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

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
}
Run Code Online (Sandbox Code Playgroud)

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

[ValidateEmailIf("IsReminderChecked", true)]
public bool EmailAddress { get; set; }
Run Code Online (Sandbox Code Playgroud)