Subscribe to Youtube channel

Validations using entity framework data annotation in .Net core MVC

 In previous article we have learnt about working with Drop down in .Net Core MVC. now in this article we will work with the validations using entity framework data annotation. To implement the validation we just need to write minimal code and you are done, you do not need to write extra code for handling validation of your form. 



Lets start the implementation, I am going to use the same application for this implementation which i have used in previous article mentioned above.

We will use below validation types in this article however there are more validation types available in entity framework data annotation (like Range validation,compare validation,Custom Validation and more)  .

  • Required validation
  • Regular Expression validation
  • String Length validation
  • Max Length validation 

First we need to import "_ValidationScriptsPartial" partial class in our view where we need to implement the validation using below syntax.

 @Html.Partial("_ValidationScriptsPartial")  

In View we need to use ValidationMessageFor control to show the validation for each field as per below syntax.

  @Html.ValidationMessageFor(model => model.Name)  

so above changes required in view page where we want to implement the validation. Following is the complete code of view page SaveEmployee.chtml file


 @*  
   For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860  
 *@  
 @using ModelsExample  
 @model Employee  
 @{  
 }  
 @section Scripts  
 {  
   @Html.Partial("_ValidationScriptsPartial")  
   <script type="text/javascript">  
     $(document).ready(function () {  
       $("#StateId").change(function () {  
         var stateId = $(this).val();  
         $.get("/MasterData/GetCity?StateId=" + stateId, function (data) {  
           var city = $("#CityId");  
           city.html('');  
           city.append($("<option/>", { value: "", text: "Select" }));  
           if (data && data.length > 0) {  
             $.each(data, function (index, item) {  
               city.append($("<option/>", { value: item.id, text: item.name }));  
             });  
           }  
         });  
       });  
     });  
   </script>  
 <style type="text/css">  
   .field-validation-error  
   {  
     color:red;  
     font-weight:bold;  
   }  
 </style>  
 }  
 @using (Html.BeginForm())  
 {  
   <h1>Enter Employee Details</h1>  
   <div>  
     @Html.LabelFor(model => model.Name)  
   </div>  
   <div>  
     @Html.TextBoxFor(model => model.Name)  
     @Html.ValidationMessageFor(model => model.Name)  
   </div>  
   <div>  
     @Html.LabelFor(model => model.Address)  
   </div>  
   <div>  
     @Html.TextBoxFor(model => model.Address)  
     @Html.ValidationMessageFor(model => model.Address)  
   </div>  
   <div>  
     @Html.LabelFor(model => model.StateId)  
   </div>  
   <div>  
     @Html.DropDownListFor(model => model.StateId, new SelectList(ViewBag.StateMaster, "Id", "Name", 0), "Select")  
     @Html.ValidationMessageFor(model => model.StateId)  
   </div>  
   <div>  
     @Html.LabelFor(model => model.CityId)  
   </div>  
   <div>  
     @Html.DropDownListFor(model => model.CityId, new SelectList(Enumerable.Empty<SelectListItem>(), "Id", "Name", 0), "Select")  
     @Html.ValidationMessageFor(model => model.CityId)  
   </div>  
   <hr />  
   <div>  
     <input type="submit" value="Submit" /> @Html.ActionLink("Back to employees", "Index")  
   </div>  
 }  

  

We have discussed changes needed in view page now we need to make changes in Model class of Employee where we will configure the various validations. We required to import below namespace to implement the validations.

 using System.ComponentModel.DataAnnotations;   

 To implement the validation we need to decorate each property with below attributes.

  [MaxLength(25,ErrorMessage ="Maximum 25 characters allowed")]  
  [RegularExpression(@"^[a-zA-Z0-9]{4,10}$", ErrorMessage ="Special Character not allowed in Name")]  
  [Required(ErrorMessage ="Please Enter Name")]    

In above code sample you can see that we are just defining the validation type and its settings with error message. This error message will be shown to user once any validation violation by user. following is the complete sample of Employee model.

 using System;  
 using System.ComponentModel.DataAnnotations;  
 using System.ComponentModel.DataAnnotations.Schema;  
 namespace ModelsExample  
 {  
   [Table("EmployeeMaster")]  
   public class Employee  
   {  
     [Column("Id")]  
     public int Id { get; set; }  
     [Column("Name")]  
     [MaxLength(25,ErrorMessage ="Maximum 25 characters allowed")]  
     [RegularExpression(@"^[a-zA-Z0-9]{4,10}$", ErrorMessage ="Special Character not allowed in Name")]  
     [Required(ErrorMessage ="Please Enter Name")]      
     public string Name { get; set; }  
     [Column("Address")]     
     [Required(ErrorMessage = "Please Enter Address")]  
     [StringLength(200,ErrorMessage = "{0} length must be between {2} and {1}.",MinimumLength =6)]  
     public string Address { get; set; }  
     [Column("CityId")]  
     [Required(ErrorMessage = "Please select City")]  
     public int CityId { get; set; }  
     [Column("StateId")]  
     [Required(ErrorMessage = "Please select State")]  
     public int StateId { get; set; }  
   }  
 }  

 

After above changes in model we also need to do the changes in our controller where we will check for validation at action level whether the model which is sent from view is valid or not, for that we need to check the value of ModelState.IsValid property as per below code sample.

 using BusinessLayerExample.Definition;  
 using Microsoft.AspNetCore.Mvc;  
 using ModelsExample;  
 namespace Project_structiure_Example.Controllers  
 {  
   public class EmployeeController : Controller  
   {  
     public readonly IEmployeeService employeeService;  
     public readonly IMasterService masterService;  
     public EmployeeController(IEmployeeService employeeServiceObj,IMasterService masterService)  
     {  
       employeeService = employeeServiceObj;  
       this.masterService = masterService;  
     }  
     public IActionResult Index()  
     {  
       var employees = employeeService.GetEmplyees();  
       return View(employees);  
     }  
     [HttpGet]  
     public IActionResult SaveEmployee()  
     {  
       ViewBag.StateMaster= masterService.GetStateMaster();  
       return View(new Employee());  
     }  
     [HttpPost]  
     public IActionResult SaveEmployee(Employee employee)  
     {  
       bool result = false;  
       if (ModelState.IsValid)
       {  
          result = employeeService.SaveEmployee(employee);  
       }  
       if(result)  
       {  
         return RedirectToAction("Index");  
       }  
       else  
       {  
         ViewBag.StateMaster = masterService.GetStateMaster();  
         return View(employee);  
       }  
     }  
     [HttpGet]  
     public IActionResult UpdateEmployee(int id)  
     {  
       var employee = employeeService.GetEmplyees(id);  
       return View(employee);  
     }  
     [HttpPost]  
     public IActionResult UpdateEmployee(Employee employee)  
     {  
       var result = employeeService.UpdateEmployee(employee);  
       if (result)  
       {  
         return RedirectToAction("Index");  
       }  
       else  
       {  
         return View(employee);  
       }  
     }  
     [HttpGet]  
     public IActionResult DeleteEmployee(int id)  
     {  
       var employee = employeeService.GetEmplyees(id);  
       return View(employee);  
     }  
     [HttpPost]  
     public IActionResult DeleteEmployee(int id,Employee emp)  
     {  
       var result = employeeService.DeleteEmployee(id);  
       if (result)  
       {  
         return RedirectToAction("Index");  
       }  
       else  
       {  
         return View(emp);  
       }  
     }  
   }  
 }  

 In above code we have checked that whether the ModelState is valid or not, if it is invalid then we will not call SaveEmployee method insted we will return the user to same page with the error message.

That's it, with the above minimal code changes we have implemented validations in my page. Lets check out the output as per below screen shots.

validation 1 output
validation 2 output




 

Comments

Popular posts from this blog

Root your Gingerbread 2.3.4 android Mobile Phone

Implement Logging in CSV file using Nlog in .net core MVC application- part 2

Disable backspace key using Jquery

Restore the lost focus of Auto post back controls in asp.net update Panel control

Implement Nlog in .Net core MVC application part 1

Devexpress Datebox date formatting in angular 6 with example

Angular User Session Timeout example step by step

How to Import CSV File and bind csv file data to gridview in asp.net using c#

Add Comma automatically while entering amounts in textbox using Javascript