好吧,在我看来,您将需要 CompositionType.Or 和一个否定 bool 字段值的自定义验证器:
[ValidatorComposition(CompositionType.Or)]
[FalseFieldValidator("EnabledField")]
[RegexValidator("\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*", MessageTemplate = "Invalid Email Address")]
public String Email_NotificationUser { get; set; }
然后简化的验证属性和逻辑代码将如下所示:
[AttributeUsage(AttributeTargets.Property)]
public class FalseFieldValidatorAttribute: ValidatorAttribute {
protected override Validator DoCreateValidator(Type targetType) {
return new FalseFieldValidator(FieldName);
}
protected string FieldName { get; set; }
public FalseFieldValidatorAttribute(string fieldName) {
this.FieldName = fieldName;
}
}
public class FalseFieldValidator: Microsoft.Practices.EnterpriseLibrary.Validation.Validator {
protected override string DefaultMessageTemplate {
get { return ""; }
}
protected string FieldName { get; set; }
public FalseFieldValidator(string fieldName) : base(null, null) {
FieldName = fieldName;
}
public override void DoValidate(object objectToValidate, object currentTarget, string key, ValidationResults validationResults) {
System.Reflection.PropertyInfo propertyInfo = currentTarget.GetType().GetProperty(FieldName);
if(propertyInfo != null) {
if((bool)propertyInfo.GetValue(currentTarget, null))
validationResults.AddResult(new Microsoft.Practices.EnterpriseLibrary.Validation.ValidationResult(String.Format("{0} value is True", FieldName), currentTarget, key, null, this));
}
}
}
在这种情况下,FalseFieldValidator
只要 EnabledField 为真并且“或”条件将RegexValidator
有机会触发,它将失败。