views:

72

answers:

1

I'm having problems validating an email address in my View Model. Property I'm checking is -

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

What I cannot figure out how to code the line "[SOME Operator("EnabledField")]". What I'm trying to do is that if EnabledField checkbox is clicked, then validate this field for being a valid e-mail address.

Edit note - Changed Condition from Or to And

A: 

Well, in my opinion you will need CompositionType.Or and a custom validator that negates bool field value:

[ValidatorComposition(CompositionType.Or)]
[FalseFieldValidator("EnabledField")]
[RegexValidator("\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*", MessageTemplate = "Invalid Email Address")]
public String Email_NotificationUser { get; set; }

Then simplified validation attribute and logic code will be along the lines of:

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

    protected 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));
        }
    }
}

In this scenario the FalseFieldValidator will fail whenever EnabledField is true and "Or" condition will give RegexValidator a chance to fire.

Stanislav Kniazev