[英]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.