0

我在验证视图模型中的电子邮件地址时遇到问题。我正在检查的财产是-

    [ValidatorComposition(CompositionType.And)]
    [SOME Operator("EnabledField")]
    [RegexValidator("\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*", Ruleset = "RuleSetA",
        MessageTemplate = "Invalid Email Address")]
    public String Email_NotificationUser
    {
        get { return _Email_NotificationUser; }
        set
        {
            _Email_NotificationUser = value;
            RaisePropertyChanged("Email_NotificationUser");
        }
    }

我无法弄清楚如何对“[SOME Operator("EnabledField")]”行进行编码。我要做的是,如果单击 EnabledField 复选框,则验证此字段是否为有效的电子邮件地址。

编辑注释 - 将条件从或更改为和

4

1 回答 1

1

好吧,在我看来,您将需要 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有机会触发,它将失败。

于 2010-01-18T21:13:02.223 回答