---
title: "how to use data validation in mvc core"  
description: "Today, we will learn how to use data annotation and validate the data before saving in your database. So we need to first understand what is data anno"  
author: "Anonymous User"  
published: 2019-05-25  
updated: 2019-12-24  
canonical: https://www.mindstick.com/articles/85566/how-to-use-data-validation-in-mvc-core  
category: "asp.net"  
tags: ["mvc5"]  
reading_time: 9 minutes  

---

# how to use data validation in mvc core

Today, we will learn how to use data annotation and validate the data before saving in your database. So we need to first understand what is data annotation? What is Data Annotation? "Data Annotation provides attribute classes that are used to define metadata for ASP.NET MVC and ASP.NET data controls." Let's see it now. In this example, we are going to use data annotation to validate model data before submitting the form. So, you need to create your [database first in SQL Server](https://www.mindstick.com/articles/71/how-to-create-xml-file-of-database-in-c-sharp). To create a new database first open “Microsoft SQL Server Management Studio” and right-click on Database node and choose New Database. Open New Query window and execute the following code in the query window:

```
create database TechMindCore
```

Create a table in Database like below:

```
 CREATE TABLE Movie
(
ID bigint primary key identity(1,1),
Title  nvarchar(100),
ReleaseDate  DateTime,
Genre  nvarchar(100),
Price Decimal(10,2)
)
```

Now Open Visual Studio 2017 and let’s create a new ASP.NET Core Web Application project. To do this, Select File > New > Project. In the New Project dialog select Visual C# > Web > ASP.NET Core Web Application just like in the figure below: ![how to use data validation in mvc core](https://www.mindstick.com/mindstickarticle/0138f636-399b-44dd-b7d9-b47fd5aeb236/images/91bf6c32-9845-448f-89b5-646d00e75c3e.png)\
Figure 1: ASP.NET Core Web Application Project Template Name your project to whatever you like, but for this exercise, we will name it as “AspDotNetCoreMvc” to confirm with the topic. Click OK and then select “[**Web Application (Model-View-Controller)**](https://www.mindstick.com/articles/1385/editable-grid-view-system-using-bootstrap-in-asp-dot-net)” within ASP.NET Core templates as shown in the following figure below: ![how to use data validation in mvc core](https://www.mindstick.com/mindstickarticle/0138f636-399b-44dd-b7d9-b47fd5aeb236/images/c5cd68c2-ee22-4b57-82d1-bfb4b82a77f5.png) Figure 2: ASP.NET Core Web Application Template Now click on Change Authentication box. Select the individual User Accounts options and then click the OK button to let Visual Studio generate the required files needed for us to run the application. The figure below shows the default generated files: ![how to use data validation in mvc core](https://www.mindstick.com/mindstickarticle/0138f636-399b-44dd-b7d9-b47fd5aeb236/images/b06d8690-ff2b-41b2-8a7f-2c100d231c58.png) Figure 3: The Models ,Views and Controller Now, open the appsettings.json file and provide the database name, database server name, and related credentials to establish the connection with the database.

```
{
  "ConnectionStrings": {
    "DefaultConnection": "Password=sa@123;Persist Security Info=True;User ID=sa;Initial Catalog=TechMindCore;Data Source=(local)"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }
}
```

Integrating Entity Framework Core Now, in order to import existing database context object using entity framework to my core web application, I need to install the following library packages via "Tools->NuGet Package Manager->Manage NuGet Packages for Solution". Now, right-click on the root of your application and then select Manage NuGet Packages. Select the Browse tab and in the search bar, type in “Microsoft.EntityFrameworkCore.SqlServer”. It should result to something like this: ![how to use data validation in mvc core](https://www.mindstick.com/mindstickarticle/0138f636-399b-44dd-b7d9-b47fd5aeb236/images/1c89ce55-5b3f-499b-b6df-5e94f5b60da2.png) Figure 4: Manage NuGet Package we are going to use Database-First development approach to work with existing database, we need to install the additional packages below as well: • Microsoft.EntityFrameworkCore.Tools (v2.0.1) • Microsoft.EntityFrameworkCore.SqlServer.Design (v1.1.4) Using Nuget Package Manager GUI Go to Tools > NuGet Package Manager > Manage NuGet Packages for Solution, then type in "Microsoft.EntityFrameworkCore.Tools”. Click install just like in the figure below: ![how to use data validation in mvc core](https://www.mindstick.com/mindstickarticle/0138f636-399b-44dd-b7d9-b47fd5aeb236/images/65f31cd5-4845-454c-9682-2d6ffb0bfdc9.png) Figure 5: Adding Microsoft.EntityFrameworkCore.Tools package When it’s done installing all the required packages, you should be able to see them added to your project dependencies as shown in the figure below: ![how to use data validation in mvc core](https://www.mindstick.com/mindstickarticle/0138f636-399b-44dd-b7d9-b47fd5aeb236/images/143199c1-aa3e-49f1-b9cf-6a7a83f63cbf.png) Figure 6: Entity Framework Core Packages installed Creating Entity Models from Existing Database Using Package Manager Console Now Click "Tools->NuGet Package Manager->Package Manager Console" as shown below: ![how to use data validation in mvc core](https://www.mindstick.com/mindstickarticle/0138f636-399b-44dd-b7d9-b47fd5aeb236/images/b958e3a4-36d9-4e30-948e-d0923e758fe4.png) Figure 7: Console Manager Package Type the following command inside the console as shown below. Scaffold-DbContext "Server=(local);Database=TechMindCore;Trusted_Connection=True;user id=sa;password=sa@123;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models/DataBase ![how to use data validation in mvc core](https://www.mindstick.com/mindstickarticle/0138f636-399b-44dd-b7d9-b47fd5aeb236/images/0fea014f-158c-411f-b77a-8dd92148c8bc.png) Figure 8: Console Manager Package window The Server attribute above is the SQL server instance name. You can find it in SQL Management Studio by right clicking on your database. For this example, the server name is “(local)”. The Database attribute is your database name. In this case, the database name is “TechMindCore”. The –OutputDir attribute allows you to specify the location of the files generated. In this case, we’ve set it to Models/DataBase. The command above will generate models from existing database within Models/DB folder. Here’s the screenshot below: ![how to use data validation in mvc core](https://www.mindstick.com/mindstickarticle/0138f636-399b-44dd-b7d9-b47fd5aeb236/images/64bef055-0f1a-4bd1-b85a-1a94aa77a12b.png) Figure 9: database context object Output. Now see above highlighted File “TechMindCoreContext.cs” DbContext Generated successfully. Now create a MovieMetadata model class to define data annotation validation attribute.

```
 using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication1.Models.DataBase
{
    [ModelMetadataType(typeof(MovieMetadata))]
    public partial class Movie
    {
    }
    public class MovieMetadata
    {
        public long Id { get; set; }
        [Required(ErrorMessage = "Title is required")]
        public string Title { get; set; }

        [Required(ErrorMessage = "Date is required")]
        public DateTime ReleaseDate { get; set; }

        [Required(ErrorMessage = "Genre must be specified")]
        public string Genre { get; set; }

        [Required(ErrorMessage = "Price is required")]
        [Range(1, 100, ErrorMessage = "Price must be between $1 and $100")]
        public decimal Price { get; set; }
    }
}
```

Creating View and Controller The next step is to create UI. In this step, I have created Controller and View. I have “MovieController.cs” file under the Controllers folder and created two Views under the “Views” folder. Following snap is showing the hierarchy of folders and files within our project. ![how to use data validation in mvc core](https://www.mindstick.com/mindstickarticle/0138f636-399b-44dd-b7d9-b47fd5aeb236/images/0f5a2110-ff03-4c25-a44c-5fb64c26ddbc.png) Figure 10: ASP.NET Core controller and view Following is the code snippet for MovieController. MovieController.cs

```
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models.DataBase;
namespace WebApplication1.Controllers
{
    public class MovieController : Controller
    {
        TechMindCoreContext db = new TechMindCoreContext();


        public IActionResult Create()
        {
            ViewBag.title = "Create";
            return View();
        }
            [HttpPost]
        public IActionResult Create(Movie model)
        {
            ModelState.Remove("Id");
            if (ModelState.IsValid)
            {
                if (model.Id <= 0)
                {
                    db.Movie.Add(model);
                }
                else
                {
                    var movie = db.Movie.FirstOrDefault(x => x.Id == model.Id);
                    movie.Title = model.Title;
                    movie.Price = model.Price;
                    movie.Genre = model.Genre;
                    movie.ReleaseDate = model.ReleaseDate;
                }
                db.SaveChanges();
                return RedirectToAction("Index", "Movie");
            }
            return View();

        }


    }
}
```

Create add /edit view Now, I am defining the "Add/Edit" View. The following is the code snippet for "Create.cshtml". Create.cshtml

```
@model WebApplication1.Models.DataBase.Movie

@{
    ViewData["Title"] = "Create";
    Layout = "~/Views/Shared/_Layout.cshtml";

}

<h2>Create/Edit Movie</h2>
<h4>Movie</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <input asp-for="Id" class="form-control" type="hidden" />
            </div>
            <div class="form-group">
                <label asp-for="Title" class="control-label"></label>
                <input asp-for="Title" class="form-control" />
                <span asp-validation-for="Title" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="ReleaseDate" class="control-label"></label>
                <input asp-for="ReleaseDate" class="form-control" />
                <span asp-validation-for="ReleaseDate" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Genre" class="control-label"></label>
                <input asp-for="Genre" class="form-control" />
                <span asp-validation-for="Genre" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Price" class="control-label"></label>
                <input asp-for="Price" class="form-control" />
                <span asp-validation-for="Price" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Save" class="btn btn-default" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
```

Now build and run the application using CTRL + 5. In the browser, navigate to /movie/create. It should bring up the following page. When you click on save button without filling form it will so required error. ![how to use data validation in mvc core](https://www.mindstick.com/mindstickarticle/0138f636-399b-44dd-b7d9-b47fd5aeb236/images/b8bebf76-d811-41cd-ace1-e7d389ea79e9.png) Now, in this article, we learn the data annotation validation step by step in ASP.NET Core. I hope, this will help the readers to understand how to complete validation in asp.net mvc core. \

---

Original Source: https://www.mindstick.com/articles/85566/how-to-use-data-validation-in-mvc-core

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
