Adding validation

# Validation Attributes

The DataAnnotations namespace (System.ComponentModel.DataAnnotations) provides a set of built-in validation attributes that are applied declaratively to a class or property. DataAnnotations also contains formatting attributes like DataType that help with formatting and don't provide any validation.

Add validation rules to the movie model

Update the Movie class to take advantage of the built-in Required, StringLength, RegularExpression, and Range validation attributes.

using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace MvcMovie.Models;
public class Movie
{
    public int Id { get; set; }

    [StringLength(60, MinimumLength = 3)]
    [Required]
    public string? Title { get; set; }

    [Display(Name = "Release Date")]
    [DataType(DataType.Date)]
    public DateTime ReleaseDate { get; set; }

    [Range(1, 100)]
    [DataType(DataType.Currency)]
    [Column(TypeName = "decimal(18, 2)")]
    public decimal Price { get; set; }

    [RegularExpression(@"^[A-Z]+[a-zA-Z\s]*$")]
    [Required]
    [StringLength(30)]
    public string? Genre { get; set; }
}

What the above attributes do

The validation attributes specify behavior that you want to enforce on the model properties they're applied to:

  • The RegularExpression attribute is used to limit what characters can be input. In the preceding code, "Genre":

    • Must only use letters.

    • The first letter is required to be uppercase. White spaces are allowed while numbers, and special characters are not allowed

  • Value types (such as decimal, int, float, DateTime) are inherently required and don't need the [Required] attribute.

Attributes like DataType help with formatting and don't provide any validation.

Value types (such as decimal, int, float, DateTime) are inherently required and don't need the [Required] attribute.

Validation Error UI

Run the app and navigate to the Movies controller.

Select the Create New link to add a new movie. Fill out the form with some invalid values. As soon as jQuery client-side validation detects the error, it displays an error message.

Notice how the form has automatically rendered an appropriate validation error message in each field containing an invalid value. The errors are enforced both client-side (using JavaScript and jQuery) and server-side (in case a user has JavaScript disabled).

A significant benefit is that you didn't need to change a single line of code in the MoviesController class or in the Create.cshtml view in order to enable this validation UI!

Last updated