Enable client side validation in ASP.NET MVC

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.

  1. 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.
  2. 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; }
    }
}
  1. 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);
        }
    }
}
  1. Next, create a view for the form. This can be done by right-clicking on the Index action method and selecting "Add View".
  2. 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)
}
  1. 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")
    }
  1. 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"/>

 
About Us | Terms of Use | Privacy Policy | Disclaimer | Contact Us Copyright © 2012-2024 CodingFusion
50+ C# Programs for beginners to practice