Search code examples
c#data-annotations

Limit Keys in a dictionary and number of characters of its value using Data Annotations


Below is my request body for POST call to my web API.

  {
    "region" : "us-east-2",
    "namespaceName" : "com.xyx.demo.test",
    "tags": {
        "description": "Test Namespace",
        "purpose": "To store demo objects",
        ....
    }
  }

Here is the class that I am using to bind this request.

    public class Input
    {
        public string Region { get; set; }

        public string NamespaceName { get; set; }

        [Description("A set of key value pairs that define custom tags.")]
        public Dictionary<string, string> Tags { get; set; }
    }

I want to restrict my Tags Dictionary to create only 10 keys and each key's value should have not more than 256 characters.

So my ModelState should be invalid if more than 10 keys are provided or value contains more than 256 characters.

How can I do this using Data annotations ?


Solution

  • You create a custom validation attribute

    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
    public class YourAttribute : ValidationAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (!(value is Dictionary<string, string>))
                return new ValidationResult("Object is not of proper type");
    
            var dictionary = (Dictionary<string, string>)value;
    
            if (dictionary.Count > 10)
                return new ValidationResult("Dictionary cant have more than 10 items");
    
            foreach (var keyValuePair in dictionary)
            {
                if (keyValuePair.Value.Length > 256)
                    return new ValidationResult("Value cant be longer than 256.");
            }
    
            return ValidationResult.Success;
        }
    }
    

    Then your model

     public class Input
    {
        public string Region { get; set; }
    
        public string NamespaceName { get; set; }
    
        [Description("A set of key value pairs that define custom tags.")]
        [YourAttribute]
        public Dictionary<string, string> Tags { get; set; }
    }