我有一个 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;
}
}