Search code examples
c#validationunit-testingdata-annotationsdynamic-data

How do I invoke a validation attribute for testing?


I am using the RegularExpressionAttribute from DataAnnotations for validation and would like to test my regex. Is there a way to invoke the attribute directly in a unit test?

I would like to be able to do something similar to this:

public class Person
{
    [RegularExpression(@"^[0-9]{3}-[0-9]{3}-[0-9]{4}$")]
    public string PhoneNumber { get; set; }
}

Then in a unit test:

[TestMethod]
public void PhoneNumberIsValid
{
    var dude = new Person();
    dude.PhoneNumber = "555-867-5309";

    Assert.IsTrue(dude.IsValid);
}

Or even

Assert.IsTrue(dude.PhoneNumber.IsValid);

Solution

  • I ended up using the static Validator class from the DataAnnotations namespace. My test now looks like this:

    [TestMethod]
    public void PhoneNumberIsValid()
    {
        var dude = new Person();
        dude.PhoneNumber = "666-978-6410";
    
        var result = Validator.TryValidateObject(dude, new ValidationContext(dude, null, null), null, true);
    
        Assert.IsTrue(result);
    }