In this article I will explain with an example, how to validate maximum character length in ASP.Net MVC.
Note: For beginners in ASP.Net MVC, please refer my article ASP.Net MVC Hello World Tutorial with Sample Program example.
 
 

Regular Expression (Regex) to validate maximum character length

Following RegularExpression (Regex) validates maximum character length.
^[\s\S]{0,8}$
 
 

Model

The following Model class consists of one property Name. The property is decorated with the following Data Annotation attribute for performing validation.
1. RegularExpression Data Annotation attribute.
Note: The Data Annotations attribute can be used with the Entity Data Model (EDM), LINQ to SQL, and other data models.
 
The RegularExpression Data Annotation attribute have been specified with a property ErrorMessage with a string value. As the name suggests, this string value will be displayed to the user when the respective validation fails.
The RegularExpression Data Annotation attribute has been set with a RegularExpression for validating Name.
The following conditions must satisfy for a Name to be termed as valid.
1. It should be 8 Alphabets long.
2. Matches any whitespace character.
Valid example: ASPSNIPPETS.
using System.ComponentModel.DataAnnotations;
namespace MaxValidation_MVC.Models
{
    public class Person
    {
        [RegularExpression(@"^[\s\S]{8,}$", ErrorMessage = "Maximum 8 characters required.")]
        public string Name { get; set; }
    }
}
 
 

Controller

The Controller consists of following Action methods.

Action method for handling GET operation

Inside this Action method, simply the View is returned.
 

Action method for handling POST operation

This Action method handles the POST operation and when the form is submitted, the object of the Person model class is sent to this method.
The state of the submitted Model is checked using ModelState.IsValid property.
Note: ModelState.IsValid property is an inbuilt property which verifies two things:
1. Whether the Form values are bound to the Model.
2. All the validations specified inside Model class using Data annotations have been passed.
 
public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    public IActionResult Index(Person person)
    {
        if (ModelState.IsValid)
        {
            // Validation success.
        }
 
        return View();
    }
}
 
 

View

Inside the View, in the very first line the Person model class is declared as Model for the View.
The View consists of an HTML Form which has been created using the Html.BeginForm method with the following parameters.
ActionName – Name of the Action. In this case the name is Index.
ControllerName – Name of the Controller. In this case the name is Home.
FormMethod – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
 
The Form consists of a following HTML Helper functions.
1. Html.TextBoxFor – Creating a TextBox for the Model property.
2. Html.ValidationMessageFor – Displaying the Validation message for the property.
 
Submitting the Form
There is also a Submit button which when clicked, the Form gets submitted and the Name value is sent to the Controller.
@model MaxValidation_MVC.Models.Person
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    @using (Html.BeginForm("Index", "Home", FormMethod.Post))
    {
        <span>Name:</span>
        @Html.TextBoxFor(m => m.Name, "")
        @Html.ValidationMessageFor(m => m.Name, "", new { @class = "error" })
        <hr />
        <input type="submit" value="Submit" />
    }
</body>
</html>
 
 

Screenshot

ASP.Net MVC: Maximum character length validation
 
 

Demo

 
 

Downloads