In this article I will explain with an example, how to validate minimum and maximum character length in ASP.Net MVC.
Regular Expression (Regex) to validate minimum and maximum character length
^[\s\S]{5,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 following conditions must satisfy for a Name to be termed as valid.
1. It should be greater than 5 characters and less than 8 characters.
2. Matches any whitespace character.
Valid example: MUDASSAR.
using System.ComponentModel.DataAnnotations;
namespace MinMaxValidation_MVC.Models
{
public class Person
{
[RegularExpression(@"^[\s\S]{5,8}$", ErrorMessage = "Minimum 5 and 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 ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult 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 MinMaxValidation_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
Demo
Downloads