Lesson Weekend

We can easily add a few basic validations to either an MVC web application or an API. The .NET MVC framework provides several built-in data annotations that we can add to a model. Specifically, we can add one of the following validations to a model:

  • Required: Makes a field required.
  • StringLength: Determines a maximum length for a string.
  • Range: Determines a maximum and minimum for a numeric field.

Here's how we might incorporate them into our Animal class:

using System.ComponentModel.DataAnnotations;

namespace CretaceousPark.Models
    public class Animal
        public int AnimalId { get; set; }
        public string Name { get; set; }
        public string Species { get; set; }
        [Range(0, 200, ErrorMessage = "Age must be between 0 and 200.")]
        public int Age { get; set; }
        public string Gender { get; set; }
  • We add using System.ComponentModel.DataAnnotations; in order to access data annotations.

  • We add the [Required] annotation for any fields that should be required in our application.

  • We specify that a Name can't be longer than twenty characters with [StringLength(20)].

  • We provide a Range between 0 and 200 for Age. Note that we can also add a custom error message with ErrorMessage. If we don't provide a custom message, Entity will provide its own error message. For instance, if we make a POST call where the Name property is more than twenty characters, we'll get the following response:

    "errors": {
        "Name": [
            "The field Name must be a string with a maximum length of 20."
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "0HLOLVJT60FKC:00000001"

While these basic validations are helpful, there are many other validations we might want to use that .NET doesn't provide. In that situation, we can consider custom validations or use an external library.

For more information on both custom validations and validations in general, check out the official documentation.

If you are interested in exploring an external library, check out FluentValidation.

Lesson 9 of 22
Last updated April 6, 2022