VA validator for xVal ComparisonRule

Coordinator
Mar 2, 2009 at 7:34 PM
Edited Mar 2, 2009 at 7:36 PM
This discussion was initiated by an email request. I've copied it to here to share with other VA users.

>new version of xVal has the support for comparison validators (e.g., “PasswordConfirm” must equal “Password”)
>How it could be used in ValidationAspects ?


I've quickly put together the following code which should do the job. Integration with xVal is currently untested and the code is far from production quality. This validator will make its way into VA in some form in the future.

[AttributeUsage(AttributeTargets.Property)]
public class EqualToAttribute : ValidatorAttribute
{
    private readonly IValidatorFactory _validatorFactory;

    public EqualToAttribute(Type type, string property)
    {
        _validatorFactory = new EqualTo {Property = type.GetProperty(property, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)};
    }

    public override IValidatorFactory Factory
    {
        get { return _validatorFactory; }
    }
}

public class EqualTo : ValidatorFactoryBase<string>
{
    public PropertyInfo Property { get; set; }

    protected override Action<string, IValidationContext> ValidateAction
    {
        get
        {
            return (v, c) =>
                   {
                       if (v != null && v != (string)Property.GetValue(c.Instance, null))
                           throw new ValidationException("your message here");
                   };
        }
    }
}

[Validate]
public class Dummy
{
    public string NewPassword { get; set; }

    [EqualTo(typeof(Dummy), "NewPassword")]
    public string ConfirmPassword { get; set; }
}


public class TestEqualTo
{
    public void Test_Usage()
    {
        Dummy dummy = new Dummy {NewPassword = "password"};

        try
        {
            dummy.ConfirmPassword = "notpassword";
        }
        catch (ValidationException e)
        {
            // do something
        }
    }
}

The EqualTo validator will check the string value (v) is equal to the value of the property (Property) of the validation context instance (c.Instance) being validated. Note there is no checking that the property PropertyType is a string - like I said, this isn't production quality code!

to integrate with xVal you would need to add the following to the ValidationAspectsRulesProvider
Emit<Rule>.For<EqualTo>(x => new ComparisonRule(x.Property.Name, ComparisonRule.Operator.Equals));

Important: I haven't tested xVal integration (real busy right now!) but I think it should work.


Coordinator
Mar 2, 2009 at 7:43 PM
This discussion has been copied to a work item. Click here to go to the work item and continue the discussion.