Client-side validation is a process that verifies the user's input on the client's browser, reducing the load on the server. Here's a step-by-step guide to enable client-side validation in .NET MVC.
- First, create a new .NET MVC project and add a model to it. In this example, we will be using a simple model with three properties: Name, Age, and Email.
- Add the following code to the model:
using System;
using System.ComponentModel.DataAnnotations;
namespace ClientSideValidation.Models
{
public class User
{
[Required]
public string Name { get; set; }
[Range(18, 100)]
public int Age { get; set; }
[EmailAddress]
public string Email { get; set; }
}
}
- In the Controller, create an action method to handle the form submission:
using System.Web.Mvc;
using ClientSideValidation.Models;
namespace ClientSideValidation.Controllers
{
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(User user)
{
if (ModelState.IsValid)
{
//process the form
}
return View(user);
}
}
}
- Next, create a view for the form. This can be done by right-clicking on the Index action method and selecting "Add View".
- Add the following code to the view:
@model ClientSideValidation.Models.User
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.LabelFor(m => m.Name)
@Html.TextBoxFor(m => m.Name, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Name)
@Html.LabelFor(m => m.Age)
@Html.TextBoxFor(m => m.Age, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Age)
@Html.LabelFor(m => m.Email)
@Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Email)
}
- Now, add the following code to the head section of the view to include the required client-side validation scripts:
Note: You can also add these scripts in your "Views=>Shared=>_Layout.chtml" page in order to enable validation on all the pages.
@section Scripts {
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
}
- Now, add the following two settings in the
section of web.config, if they are not there:
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>