DEV Community

Cover image for Explain Model Validation Using Data Annotation in ASP.NET MVC
Harshal Suthar
Harshal Suthar

Posted on • Originally published at ifourtechnolab.com

Explain Model Validation Using Data Annotation in ASP.NET MVC

What is Data Validation?

Data Validation is an important aspect of developing web applications. It is used to check whether the user data entered is valid or not. To work on this, ASP.NET MVC offers Data Annotation attribute classes to modal class.

What are Data Annotations?

Data annotations are nothing but certain validations that are used with models to validate the user input from users. Data Annotation attribute classes are present in System.ComponentModel.DataAnnotations namespace is a powerful way to check for errors and, if necessary, display messages to the user.

Types of Data Annotations in ASP.NET MVC

Require

This type of attribute specifies that the value cannot be skipped, user needs to enter the value for this field.

Syntax
[Required(ErrorMessage=Message),MaxLength(int)]

Here MaxLength is option parameter

Example
[Required(ErrorMessage = Name is Required ), MaxLength(20)]

[Required(ErrorMessage = "Email ID is Required")]

DataType

This type of attribute specifies that the value cannot be skipped, user needs to enter the value for this field.

Syntax
[DataType(DataType.Text)]

Example
[DataType(DataType.Currency)]

[DataType(DataType.Date)]

StringLength

This type of attribute is used to specify the size of the column.

The StringLength attribute specifies the minimum and maximum length of the property.StringLength similar to a minimum and maximum length attributes but used only with string type properties.

Syntax
[StringLength(MaximumLength, MinimumLength = value)]

[StringLength(MaximumLength, MinimumLength =value, ErrorMessage = "Message”)]

Example
[StringLength(50, MinimumLength = 10)]

[StringLength(50, MinimumLength = 10, ErrorMessage = Do not enter more than 50 character and less than 10 character)]

Range

Using this attribute, we can specify the minimum and maximum value for a numeric value.

Syntax
[Range(minimum,maximum,ErrorMessage=Message)]

Example
[Range(18,60,ErrorMessage=Age must between 18 to 60 )]

DisplayName

This type of attribute allows us to specify the property name displayed on the view.

Syntax
[Display(Name=Name Display on View)]

Example
[Display(Name=First Name)]

DisplayFormat

This attribute allows us to set the format specified as per the attribute.

Syntax
[DisplayFormat(DataFormatString = specify format )]

Example
[DisplayFormat(DataFormatString = {0:dd.MM.yyyy})]

MaxLength

Using this attribute, we can specify the maximum length of the property.

Syntax
[MaxLength(value)]

Example
[MaxLength(50,ErrorMessage="Description cannot be greater than 50")]

MinLength

This type of attribute is used to specify the minimum length of string or an array property

Syntax
[MinLength(value)]

Example
[MinLength(20)]

[MinLength(20,ErrorMessage=Description cannot be less than 50)]

Bind

This type of attribute specifies fields to include and exclude properties for model binding.

Example
[Bind(Exclude = UserId)]

[Bind(Include = UserId,Name,Email,Gender)]

Read More: Explain Forms Authentication In Asp.net Mvc

RegularExpression

We can set a pattern for the property for Ex we can set RegularExperssion for Email String

Example
[RegularExpression(@^\w+([-+.']\w+)@\w+([-.]\w+).\w+([-.]\w+)*$, ErrorMessage = Enter Valid Email)]

Create MVC Application for Data Annotation Demo

Now, we need to create an MVC application for the data annotation demo. Create a new MVC application and inside the model, folder add a new class for model.

Right, click on model, click on add, and select class.

Image description

Employee class


using System;
using System.ComponentModel.DataAnnotations;

namespace Dynamicappendpartial.Models
{
    public class Employee
    {
        public int E_Id { get; set; }

        [Required(ErrorMessage = "name  Required")]
        [Display(Name = "Full Name")]
        [MaxLength(30), MinLength(10)]
        public string Name { get; set; }

        [Required(ErrorMessage = "gender Required")]
        public string Gender { get; set; }

        [Required(ErrorMessage = "Email Address Required")]
        [Display(Name = "Email Address")]
        [EmailAddress]
        public string EmailAddress { get; set; }

        [Required(ErrorMessage = "Postion Required")]
        public string Position { get; set; }

        [Required(ErrorMessage = "Hire Date Required")]
        [Display(Name = "Hire date")]
        [DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}")]
        public DateTime HireDate { get; set; }

        [Required(ErrorMessage = "salary Required")]
        [DataType(DataType.Currency)]
        [Range(15000, 60000, ErrorMessage = "salary must between 15000 to 60000")]
        public int Salary { get; set; }

        [Required(ErrorMessage = "Website Required")]
        [Display(Name = "Personal Website")]
        [Url]
        public string WebSite { get; set; }
    }
}

Enter fullscreen mode Exit fullscreen mode

Add controller inside the controller folder.

EmployeeController

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Dynamicappendpartial.Models;

namespace Dynamicappendpartial.Controllers
{
    public class EmployeesController: Controller
    {
        private PartialDbContext db = new PartialDbContext();

        public ActionResult Index()
        {
            return View(db.Employees.ToList());
        }

        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Employee employee = db.Employees.Find(id);
            if (employee == null)
            {
                return HttpNotFound();
            }
            return View(employee);
        }

        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,Name,Gender,EmailAddress,Position,HireDate,Salary,WebSite")] Employee employee)
        {
            if (ModelState.IsValid)
            {
                db.Employees.Add(employee);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(employee);
        }
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Employee employee = db.Employees.Find(id);
            if (employee == null)
            {
                return HttpNotFound();
            }
            return View(employee);
        }

        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Employee employee = db.Employees.Find(id);
            db.Employees.Remove(employee);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

Right-click on Create method and add the view for create method.

Looking for Trusted ASP.Net Software Development Company For Your Business?

Create view


        @model Dynamicappendpartial.Models.Employee

@{
    ViewBag.Title = "Create";
}<h2>Create</h2>

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()
<div class="form-horizontal"><h4>Employee</h4>
<hr>
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })<div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })<div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })</div></div>
<div class="form-group">
            @Html.LabelFor(model => model.Gender, htmlAttributes: new { @class = "control-label col-md-2" })<div class="col-md-10">
                @Html.EditorFor(model => model.Gender, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Gender, "", new { @class = "text-danger" })</div></div>
<div class="form-group">
            @Html.LabelFor(model => model.EmailAddress, htmlAttributes: new { @class = "control-label col-md-2" })<div class="col-md-10">
                @Html.EditorFor(model => model.EmailAddress, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.EmailAddress, "", new { @class = "text-danger" })</div></div>
<div class="form-group">
            @Html.LabelFor(model => model.Position, htmlAttributes: new { @class = "control-label col-md-2" })<div class="col-md-10">
                @Html.EditorFor(model => model.Position, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Position, "", new { @class = "text-danger" })</div></div>
<div class="form-group">
            @Html.LabelFor(model => model.HireDate, htmlAttributes: new { @class = "control-label col-md-2" })<div class="col-md-10">
                @Html.EditorFor(model => model.HireDate, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.HireDate, "", new { @class = "text-danger" })</div></div>
<div class="form-group">
            @Html.LabelFor(model => model.Salary, htmlAttributes: new { @class = "control-label col-md-2" })<div class="col-md-10">
                @Html.EditorFor(model => model.Salary, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Salary, "", new { @class = "text-danger" })</div></div>
<div class="form-group">
            @Html.LabelFor(model => model.WebSite, htmlAttributes: new { @class = "control-label col-md-2" })<div class="col-md-10">
                @Html.EditorFor(model => model.WebSite, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.WebSite, "", new { @class = "text-danger" })</div></div>
<div class="form-group"><div class="col-md-offset-2 col-md-10">
                <input class="btn btn-default" type="submit" value="Create"></div></div></div>
}
<div>
    @Html.ActionLink("Back to List", "Index")</div>

Enter fullscreen mode Exit fullscreen mode

Now, run the application and click on create and add details and check the model validation

Image description
[Fig:- model validation for empty field]

Image description
[Fig:- Model validation for Email]

Image description
[Fig:- Model validation for a salary]

Conclusion

In this blog, we have learned Data Annotations. It provides a list of attributes for model validation. Using different types of attributes, we create restrictions to a user if he enters data that is of invalid format or Invalid range.

Top comments (0)