WPF条件验证

时间:2010-01-18 16:40:20

标签: wpf validation enterprise-library viewmodel

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

    [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复选框,则将此字段验证为有效的电子邮件地址。

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

1 个答案:

答案 0 :(得分: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));
        }
    }
}

在这种情况下,只要EnabledField为true,FalseFieldValidator就会失败,而“或”条件会让RegexValidator有机会开火。