代码之家  ›  专栏  ›  技术社区  ›  photo_tom

WPF条件验证

  •  0
  • photo_tom  · 技术社区  · 16 年前

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

        [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");
            }
        }
    

    我无法理解如何对行“[某些运算符(“EnabledField”)]进行编码”。我要做的是,如果单击了EnabledField复选框,则验证此字段是否为有效的电子邮件地址。

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

    1 回复  |  直到 14 年前
        1
  •  1
  •   Kirk Broadhurst    14 年前

    好吧,在我看来,您需要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 一个开火的机会。