---
title: "Validation using Data Annotation using entity framework"  
description: "Data annotation is for adding extra meaning to the data. We use attribute for data annotation. There are many attribute which we use for data annotati"  
author: "Manish Kumar"  
published: 2017-01-19  
updated: 2018-11-17  
canonical: https://www.mindstick.com/articles/12234/validation-using-data-annotation-using-entity-framework  
category: "asp.net"  
tags: ["asp.net"]  
reading_time: 3 minutes  

---

# Validation using Data Annotation using entity framework

Data annotation is for adding extra meaning to the data. We use attribute for data annotation. There are many attribute which we use for data annotation. **We use data annotation** for data validating, we can validate our field by data annotation by simply adding attribute.

By data annotation we can validate our field in the UI and by using Display attribute we can specify that how data from model is displayed in view or UI.

We use system.componentmodel.DataAnnotation [namespace](https://www.mindstick.com/articles/28/namespace-in-dot-net) for using attribute of data annotation.

**Now we will take an example for data annotation.**

When we are working with data first approach. We cannot put our validation in the self-generate class from the EF because when we change our [database table](https://www.mindstick.com/forum/159366/how-to-test-regular-expressions-in-sql-without-using-database-table) our validation will lose so the right way is For data annotation to create a [class in model](https://www.mindstick.com/forum/33950/how-to-use-one-composite-key-in-a-class-to-another-class-in-model-of-asp-dot-net-mvc4-using-code-first-approach) folder and name it Metadata’s

```
using System;using System.Collections.Generic;using System.Linq;                            using System.Web;using System.ComponentModel.DataAnnotations;namespace Demo.Models{    public class EmpDetailMetaData    {               [Required(ErrorMessage = "UserName
Name is required")]        public string UserName { get; set; }        [Required(ErrorMessage = "FName Name
is required")]        public string FName { get; set; }        [Required(ErrorMessage = "Email is
required")]        public string Email { get; set; }        [Required(ErrorMessage = "Mobile is
required")]        public string Mobile { get; set; }    }}
```

## *\*

**And another [class name](https://www.mindstick.com/forum/12871/how-to-get-class-name) it partialclass**\

```
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.ComponentModel.DataAnnotations; namespace Demo.Models{              [MetadataType(typeof(EmpDetailMetaData))]        public partial class EmpDetail        {        } }
```

\

**In the above metadata class we have use [required attribute](https://www.mindstick.com/forum/158276/how-do-you-use-the-required-attribute-in-html5-to-make-form-fields-mandatory)**

**Now in the [controller](https://www.mindstick.com/blog/273/passing-values-from-controller-to-view-in-asp-dot-net-mvc) we do the logic for validation**

```
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using Demo.Models;  namespace Demo.Controllers{    public class HomeController : BaseController    {         
        public ActionResult Index()        {            ViewBag.Users = Uow.EmpDetail.SelectAll();                               return View();        }     [AcceptVerbs(HttpVerbs.Post)]        public ActionResult Index(EmpDetail model)        {            if (ModelState.IsValid)            {                if (model.Id == 0)                {                   
Uow.EmpDetail.Insert(model);                 }                else                {                    var data = Uow.EmpDetail.SelectByID(model.Id);                    if (data == null)                        Uow.EmpDetail.Insert(model);                    else                       
Uow.EmpDetail.Update(model);                }            }                ViewBag.Users =Uow.EmpDetail.SelectAll();                return PartialView("UserList");                             }    
        [HttpPost]        public ActionResult Delete(int Id)        {            Uow.EmpDetail.Delete(Id);                      ViewBag.Users = Uow.EmpDetail.SelectAll();                        return PartialView("UserList");        }             public ActionResult Edit(int Id)        {            var data = Uow.EmpDetail.SelectByID(Id);            return Json(data, JsonRequestBehavior.AllowGet);        }            }} 
```

## Now int the add view for for index method.\
@{

```
    ViewBag.Title = "Index";} @*<script
src="~/Scripts/jquery-3.1.1.min.js"></script> *@<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.js"></script><script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script><script src="~/Scripts/jquery.validate.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.2/jquery.validate.unobtrusive.js"></script>@using (Ajax.BeginForm("index", "Home", new AjaxOptions{    HttpMethod = "POST",      UpdateTargetId = "target",    OnSuccess = "updateSuccess"})){          <center><h2>Registration Form</h2></center>     @Html.ValidationSummary(true)          <hr />       <div>            <center> <table border="0"  width="70%" cellspadding="0" cellspacing="0">        <tr>             <td><label id="label1">User Name</label>                @Html.HiddenFor(x => x.Id, new {@Value=0 })            </td>              <td>@Html.TextBoxFor(x => x.UserName)                  @Html.ValidationMessageFor(m => m.UserName)              </td>            <td><label id="label2">Father Name</label></td>              <td>@Html.TextBoxFor(x => x.FName)                  @Html.ValidationMessageFor(m => m.FName)              </td>        </tr>       <tr>            <td><label id="label3">Email</label></td>              <td>@Html.TextBoxFor(x => x.Email)                  @Html.ValidationMessageFor(m=> m.Email)              </td>            <td><label id="label4">Mobile</label></td>              <td>@Html.TextBoxFor(x=> x.Mobile)                  @Html.ValidationMessageFor(m => m.Mobile)              </td>        </tr>       <tr>         <td colspan="2"> <br /> <center>               <input type="submit" value="Submit" /></center>           </td>       </tr>    </table></center>        </div>          }
```

**You can also visit these related [articles](https://www.mindstick.com/articles/12872/how-to-write-articles-of-50-and-more-a-day-quick-and-easy) and blogs**

[Crud operation in mvc using data annotation with entity framework](https://www.mindstick.com/forum/34232/crud-operation-in-mvc-using-data-annotation-with-entity-framework)

[Upload File using Model Validation in ASP.NET MVC](https://www.mindstick.com/Articles/1133/upload-file-using-model-validation-in-asp-dot-net-mvc)

---

Original Source: https://www.mindstick.com/articles/12234/validation-using-data-annotation-using-entity-framework

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
