Search code examples
asp.net-mvcattributes

Can the .NET Range and StringLength attributes be used outside of MVC applications?


I want to use the .NET StringLength and Range attributes to put constraints on various properties in my class. I wrote the following very simple code:

class AttributePlayground
{
    [StringLength(5)]
    public static String StringLengthTest { get; set; }

    [Range(10, 20)]
    public static int Age { get; set; }
}

static void Main(string[] args)
{
    AttributePlayground.StringLengthTest = "Too long!";
    AttributePlayground.Age = 34;    
}

I expected an error or an exception to fire but all works ok.

All the examples I see on the web about these attributes shows them in the context of MVC but the documentation makes no reference to it.


Solution

  • As you know attributes in .NET are just metadata that's baked into the assembly at compile time. If there's nothing that will interpret them, well, nothing will happen.

    So in the case of ASP.NET MVC for example there's a validator which interprets those attributes, like this:

    class AttributePlayground
    {
        [StringLength(5)]
        public String StringLengthTest { get; set; }
    
        [Range(10, 20)]
        public int Age { get; set; }
    }
    
    class Program
    {
        static void Main()
        {
            var attributePlayground = new AttributePlayground();
            attributePlayground.StringLengthTest = "Too long!";
            attributePlayground.Age = 34;
    
            var context = new ValidationContext(attributePlayground, null, null);
            var errors = new List<ValidationResult>();
            if (!Validator.TryValidateObject(attributePlayground, context, errors, true))
            {
                foreach (var error in errors)
                {
                    Console.WriteLine(error.ErrorMessage);
                }
            }
        }
    }
    

    But honestly if you intend to do some more serious and complex validation I would recommend you not using a declarative validation logic which is what Data Annotations are. I would recommend you FluentValidation.NET. It allows you to express much more complex validation rules in a nice manner which would have been otherwise very difficult to achieve with Data Annotations.