簡體   English   中英

我可以使用自定義驗證屬性手動驗證屬性嗎?

[英]Can I manually validate a property using a custom validation attribute?

我有一個自定義的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;
    }
}

可以根據另一個屬性的值來驗證一個屬性,但是要確保驗證引擎按照您期望的方式工作,需要克服一些困難。 Simon Ince的RequiredIfAttribute方法很好,只需將電子郵件驗證邏輯添加到IsValid方法中,就很容易將其修改為ValidateEmailIfAttribute

例如,您可以像現在一樣擁有基本驗證屬性:

public class ValidateEmailAttribute : ValidationAttribute
{
  ...
}

然后使用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
}

然后,您可能會得到類似:

[ValidateEmailIf("IsReminderChecked", true)]
public bool EmailAddress { get; set; }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM