我有一个自定义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;
}
}
答案 0 :(得分:6)
可以根据另一个属性的值验证属性,但是需要跳过几个环节以确保验证引擎按预期方式工作。 Simon Ince的RequiredIfAttribute有一个很好的方法,只需将您的电子邮件验证逻辑添加到ValidateEmailIfAttribute
方法,就可以很容易地将其修改为IsValid
。
例如,您可以拥有基本验证属性,就像现在一样:
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; }