Basic DataAnnotations Validation Example

In this example, I am using System.ComponentModel.DataAnnotations to validate my object.

I wrap two attributes around the property, one that requires a string, and one that marks the property as invalid if the String is greater than 20 chars.

[Required]
[StringLength(20)]
public string Name { get; set; }

Validating System.ComponentModel objects

We can validate the object using TryValidate on the System.ComponentModel.Validator class.

For now, we can just pass the Validator a new empty ValidationContext which is this code:

Validator.TryValidateObject(d1, new ValidationContext(d1, null, null), null, true);

Full test class below:

namespace ExampleLibrary.Tests
{

    public class SimpleCustomer
    {
        [Required]
        [StringLength(20)]
        public string Name { get; set; }
    }

    [TestClass]
    public class DirtyTests
    {
                
        [TestMethod]
        public void Customer_Name_InvalidWhenOverTwentyChars()
        {
            // assemble
            SimpleCustomer d1 = new SimpleCustomer() { Name = "01234567890123456789" };
            bool validWithTwentyChars, validOverTwentyChars;

            // act
            validWithTwentyChars = Validator.TryValidateObject(d1, new ValidationContext(d1, null, null), null, true);
            d1.Name = "012345678901234567890";
            validOverTwentyChars = Validator.TryValidateObject(d1, new ValidationContext(d1, null, null), null, true);

            // assert
            Assert.IsTrue(validWithTwentyChars);
            Assert.IsFalse(validOverTwentyChars);
        }

        [TestMethod]
        public void Customer_Name_InvalidWhenEmpty()
        {
            // assemblt
            SimpleCustomer d1 = new SimpleCustomer();
            bool validNull, validEmptyString, validFilledString;

            // act
            d1.Name = null;
            validNull = Validator.TryValidateObject(d1, new ValidationContext(d1, null, null), null, true);
            d1.Name = string.Empty;
            validEmptyString = Validator.TryValidateObject(d1, new ValidationContext(d1, null, null), null, true);
            d1.Name = "Some value";
            validFilledString = Validator.TryValidateObject(d1, new ValidationContext(d1, null, null), null, true);

            // assert
            Assert.IsFalse(validNull);
            Assert.IsFalse(validEmptyString);
            Assert.IsTrue(validFilledString);
        }
    }
}