Client Side Validation in MVC Framework

March 26, 2018 0 Comments A+ a-

ASP .Net

Client Side Validation

  • ASP.NET MVC framework also supports client side validation by using jqyery.
  • It will validate data immediate and display the error message in browser.
  • Validation should now happen on the client without a round trip to the server.
  • If the client disables javascript in the browser, then client side validation does not work but server side validation will continue to work as normal.
If you are implimenting custom validation on client side in MVC application, then same logic must be write in server side. in furture your business logic change due some reason then you have to change logic in server side as well as client logic. in case you forget to update new logic in one place then application will misbehave the functionality. I would like to suggest, don't impliment custom validation in client side.
Configuration of Client Side Validation.
  
 @Scripts.Render("~/bundles/jqueryval")
Add the above code in script section in the view.
Let's see the below example for your beter understanding.
EmployeeModel.cs
  
 public class EmployeeModel
        {
        public int Id { set; get; }
        [Required]
        public string Name { set;get; }
        [Required]
        public string Location { set; get; }
        }
EmployeeController.cs
   
 public class EmployeeController : Controller
        {
        public ActionResult Index ( )
            {
            return View();
            }
        [HttpGet]
        public ActionResult Create ( )
            {
            return View();
            }
        [HttpPost]
        public ActionResult Create (EmployeeModel Emp )
            {
            if(!ModelState.IsValid)
                {
                return View("Create", Emp);
                }
            return View();
            }
        }
Create.cshtml
   
@model MVCIntro.Models.EmployeeModel

@{
    ViewBag.Title = "Create";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

Create

@using (Html.BeginForm()) {

EmployeeModel


@Html.ValidationSummary(true)
@Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Name) @Html.ValidationMessageFor(model => model.Name)
@Html.LabelFor(model => model.Location, new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Location) @Html.ValidationMessageFor(model => model.Location)
}
@Html.ActionLink("Back to List", "Index")
@section Scripts { @Scripts.Render("~/bundles/jqueryval") }
Client Side Validation in MVC Framework
Fig - 1
Client Side Validation in MVC Framework
Fig - 2
Figure fig -1 is representing the output of application.
Fig - 2 is representing the network request between client and server.
As per the above fig - 2, define there is no network connection between client and server