Minimum length data annotation

Introduction


To validate the minimum length of a string entered by a user in ASP.NET MVC , we use the MinLengthAttribute.

MinLengthAttribute


The MinLengthAttribute allows you to specify the minimum length of string data allowed in a property.

MinLengthAttribute Usage


Following is a student entity that we will be using in this tutorial.

public class Student
{
    public int StudentId { get; set; }

    public string firstName { get; set; }
        
    public string lastName { get; set; }

    public int age { get; set; }
}

The objectif is to force the user to enter at least a 6 character string for the first name property in order to consider it as a valid input. To do that, we will associate the MinLengthAttribute annotation to our first name property as follows.

[Required]
[MinLength(6)]
public string firstName { get; set; }

Now, if a user enter a string containing less that 6 characters he will get the following error message : The field firstName must be a string or array type with a minimum length of '6'.

To implement your own custom error message for MinLengthAttribute , use the ErrorMessage property like this :

[Required]
[MinLength(6, ErrorMessage = "The first name field must be at least 6 characters long")]
public string firstName { get; set; }

Note


  • The RequiredAttribute is also necessary in order to validate the minimum length of a string by the MinLengthAttribute.
  • In order to view the error message in case the user didn't enter a valid string, you have to use the ValidationMessageFor

    @Html.ValidationMessageFor(m => m.firstName)
    for more information about this html helper, see How to display validation error messages in ASP.NET MVC

Namespace


To use the MinLengthAttribute, you have to include this namespace :

using System.ComponentModel.DataAnnotations;