Annotation for validation


Adding Validation to our Model

We'll use the following Data Annotation attributes:

  • Required – Indicates that the property is a required field
  • DisplayName – Defines the text we want used on form fields and validation messages
  • StringLength – Defines a maximum length for a string field
  • Range – Gives a maximum and minimum value for a numeric field
  • Bind – Lists fields to exclude or include when binding parameter or form values to model properties
  • ScaffoldColumn – Allows hiding fields from editor forms

Note: For more information on Model Validation using Data Annotation attributes, see the MSDN documentation athttps://go.microsoft.com/fwlink/?LinkId=159063



ASP.NET MVC Server-Side Validation

Approach 1: Manually Add Error to ModelState Object 

I create a User class under the Models folder. The User class has two properties "Name" and "Email". The "Name" field has required field validations while the "Email" field has Email validation. So let's see the procedure to implement the validation. Create the User Model as in the following:

namespace ServerValidation.Models
 {
    public class User
    {
        public string Name { get; set; }
        public string Email { get; set; }       
    }
 } 

After that, I create a controller action in User Controller (UserController.cs under Controllers folder). That action method has logic for the required validation for Name and Email validation on the Email field. I add an error message on ModelState with a key and that message will be shown on the view whenever the data is not to be validated in the model.

using System.Text.RegularExpressions;
using System.Web.Mvc; 
namespace ServerValidation.Controllers
{
    public class UserController : Controller
    {       
        public ActionResult Index()
        {           
            return View();
        }
        [HttpPost]
        public ActionResult Index(ServerValidation.Models.User model)
        {
            if (string.IsNullOrEmpty(model.Name))
            {
                ModelState.AddModelError("Name", "Name is required");
            }
            if (!string.IsNullOrEmpty(model.Email))
            {
                string emailRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                                         @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
                                            @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
                Regex re = new Regex(emailRegex);
                if (!re.IsMatch(model.Email))
                {
                    ModelState.AddModelError("Email", "Email is not valid");
                }
            }
            else
            {
                ModelState.AddModelError("Email", "Email is required");
            }
            if (ModelState.IsValid)
            {
                ViewBag.Name = model.Name;
                ViewBag.Email = model.Email;
            }
            return View(model);
        }
    }
} 

Thereafter, I create a view (Index.cshtml) for the user input under the User folder.

@model ServerValidation.Models.User
@{
    ViewBag.Title = "Index";
} 
@using (Html.BeginForm()) {
    if (@ViewData.ModelState.IsValid)
    {
        if(@ViewBag.Name != null)
        {
            <b>
                Name : @ViewBag.Name<br />
                Email : @ViewBag.Email
            </b>
        }
    }     
    <fieldset>
        <legend>User</legend> 
        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name) 
            @if(!ViewData.ModelState.IsValid)
            {       
                <span class="field-validation-error">
                @ViewData.ModelState["Name"].Errors[0].ErrorMessage</span>
            }            
        </div> 
        <div class="editor-label">
            @Html.LabelFor(model => model.Email)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Email)
            @if (!ViewData.ModelState.IsValid)
            {       
                 <span class="field-validation-error">
                 @ViewData.ModelState["Email"].Errors[0].ErrorMessage</span>
            }         
        </div>
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
} 

Approach 2: Specifying Business Rules with Data Annotation

While the first approach works quite well, it does tend to break the application's separation of concerns. Namely, the controller should not contain business logic such as, the business logic belongs in the model.

Microsoft provides an effective and easy-to-use data validation API called Data Annotation in the core .NET Framework. It provides a set of attributes that we can apply to the data object class properties. These attributes offer a very declarative way to apply validation rules directly to a model.

First, create a model named Student (Student.cs) under the Models folder and applies Data Annotation attributes on the properties of the Student class.

using System.ComponentModel.DataAnnotations;
namespace ServerValidation.Models
{
    public class Student
    {
        [Required(ErrorMessage = "Name is Required")]
        public string Name { get; set; }
        [Required(ErrorMessage = "Email is Required")]
        [RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                            @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
                            @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",
                            ErrorMessage="Email is not valid")]
        public string Email { get; set; }
    }
} 

Now, create an action method in the controller (StudentController class under the Controllers folder) that returns a view with a model after the post request.

using System.Web.Mvc;
using ServerValidation.Models;
namespace ServerValidation.Controllers
{
    public class StudentController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Index(Student model)
        {
            if (ModelState.IsValid)
            {
                ViewBag.Name = model.Name;
                ViewBag.Email = model.Email;
            }
            return View(model);
        }
    }
} 

After that, I created a view (Index.cshtml) to get student details and show an error message if the model data is not valid.

@model ServerValidation.Models.Student 
@{
    ViewBag.Title = "Index";
}
 @if (ViewData.ModelState.IsValid)
    {
        if(@ViewBag.Name != null)
        {
            <b>
                Name : @ViewBag.Name<br />
                Email : @ViewBag.Email
            </b>
        }
    } 
@using (Html.BeginForm()) {
    @Html.ValidationSummary(true) 
    <fieldset>
        <legend>Student</legend> 
        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div> 
        <div class="editor-label">
            @Html.LabelFor(model => model.Email)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Email)
            @Html.ValidationMessageFor(model => model.Email)
        </div> 
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}  

Custom validation summary


https://www.leniel.net/2013/08/customizing-aspnet-mvc-html-validation-summary-with-bootstrap-3-panel.html

Did you find this article useful?



  • Many Partial in same View

    To Display Multi Partial in same ViewYou can only return one value from a function so you can't return multiple partials from one action method.If you...

  • Display and Editor Templates - ASP.NET MVC

    When dealing with objects in an MVC app, we often want a way to specify how that object should be displayed on any given page. If that object is only ...