#003: Data Annotations for validation

I think the data annotations (sometimes known as System.ComponentModel.DataAnnotations) is a great idea; in the past I have played around with custom validation rules, but it was always difficult to find out how to trigger the validation event when you weren't in an asp.net page (webforms or mvc)
I was playing with this tonight, and quite liked how simple it all is:


using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;

namespace TestingNamespace
    public class DataAnnotationTests
        public void TryValidate_Test()
            var t = new TestObject();
            var vc = new ValidationContext(t, null, null);
            var validationResults = new List<ValidationResult>();

            var result = Validator.TryValidateObject(t, vc, validationResults, true);

            Assert.AreEqual(false, result, "Obviously failed validation");
            Assert.AreEqual(1, validationResults.Count, "It only includes the 'required' validation");

    public class TestObject
        public string ThingWord { get; set; }


Written on May 14, 2015