Jquery is client side scripting language which runs the scripts on client's browser to check user's inputs are valid or not. Before submitting the form to the server,jquery authenticate that user has entered all the valid text in input fields,so that server side load lifting can be minimized.
We will understand how to use client side validation using Jquery in our asp.net mvc application.
Example for client side validation using Jquery:
First add a model in our application which consists of the following fields:
STEP1:
EmployeeModel
using System;
using System.Web.mvc;
using System.ComponentModel.DataAnnotations;
namespace EmployeeManagementSystem.Models
{
public class Employee
{
public int EmployeeId { get; set; }
[Required]
public String EmpName { get; set; }
[Required]
[EmailAddress]
public string EmailId { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
[Required]
[DataType(DataType.Password)]
[Compare("Password", ErrorMessage = "Password and ConfirmPassword do not match")]
public string ConfirmPassword { get; set; }
public int GenderId { get; set; }
[Required]
public string Gender { get; set; }
public int CountryId { get; set; }
[Required]
public string Country { get; set; }
public int StateId{get;set;}
[Required]
public string State { get; set; }
}
}
STEP2:
Then add a controller in your application with the name Employee,In this controller we will create an actionresult method which will return the viewresult on the browser.
using System;
using System.Web.Mvc;
using EmployeeManagementSystem.Models;
namespace EmployeeManagementSystem.Controllers
{
[Authorize]
public class EmployeeController : Controller
{
[AllowAnonymous]
[HttpGet]
public ActionResult Index()
{
return view();
}
}
}
STEP3:Now add a stronglybind view which will bind the input fields with your model.
Index View:
@model EmployeeManagementSystem.Models.Employee
@{
ViewBag.Title = "Index";
}
<h2>Register</h2>
@using (Html.BeginForm("Index", "Employee", FormMethod.Post, new { id = "form" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>Employee</legend>
<div class="editor-label">
@Html.LabelFor(model => model.EmpName)
</div>
<div class="editor-field">
@Html.TextBoxFor(model => model.EmpName, new { id = "txtEmpname", @style = "width:310px;height:31px",required="required" })
@Html.ValidationMessageFor(model => model.EmpName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.EmailId)
</div>
<div class="editor-field">
@Html.TextBoxFor(model => model.EmailId, new { @style = "width:310px;height:31px", required = "required" })
@Html.ValidationMessageFor(model => model.EmailId)
</div>
<div id=div1></div>
<div class="editor-label">
@Html.LabelFor(model => model.Password)
</div>
<div class="editor-field">
@Html.TextBoxFor(model => model.Password, new { @style = "width:310px;height:31px", @type = "Password",required="required"})
@Html.ValidationMessageFor(model => model.Password)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.ConfirmPassword)
</div>
<div class="editor-field">
@Html.TextBoxFor(model => model.ConfirmPassword, new { @style = "width:310px;height:31px", @type = "Password", required = "required" })
@Html.ValidationMessageFor(model => model.ConfirmPassword)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Gender)
</div>
<div class="editor-field">
@Html.DropDownList("ddlEmpGender", new System.Web.Mvc.SelectList(ViewBag.Gender, "Value", "Text"), "Please select", new { @style = "width:310px;height:31px", required = "required" })
@Html.ValidationMessageFor(model => model.Gender)
</div>
<div class="editor-field">
@Html.HiddenFor(model => model.CountryId)
@Html.ValidationMessageFor(model => model.CountryId)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Country)
</div>
<div class="editor-field">
@Html.DropDownList("ddlEmpCountry", new System.Web.Mvc.SelectList(ViewBag.Country, "Value", "Text"), "Please select a Country", new { @style = "width:310px;height:31px", required = "required" })
@Html.ValidationMessageFor(model => model.Country)
</div>
<div class="editor-field">
@Html.HiddenFor(model => model.StateId)
@Html.ValidationMessageFor(model => model.StateId)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.State)
</div>
<div class="editor-field">
@Html.DropDownList("ddlEmpState", new SelectList(string.Empty, "Value", "Text"), "Please select a State", new { @style = "width:310px;height:31px"})
@Html.ValidationMessageFor(model => model.State)
</div>
<p>
<input type="submit" value="Save" style="margin-left: 3%;" onclick="validate()" />
</p>
</fieldset>
}
STEP4:To enable client side validation using jquery,we have to include jquery files in our view.(“jquery—3.0.0.min.js",”jquery.validate.unobtrusive.min.js","jquery.validate.min.js"></script>)
These are the minified files you will find in your scripts folder of your project,These are used to enable client side custom jquery validation in your application.
Client Side validation using Jquery in Index View:
<script src="~/Scripts/jquery-3.0.0.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script type="text/javascript" language="javascript">
$("#form").validate({
rules: {
EmpName:"required",
ddlEmpGender: "required",
ddlEmpCountry: "required",
ddlEmpState: "required",
Password:
{
minlength: 5
},
ConfirmPassword: {
minlength: 5,
equalTo: '[name="Password"]'
},
},
messages: {
ddlEmpGender: "Please select Gender",
ddlEmpCountry: "Please select Country",
ddlEmpState: "Please select State",
Password: "Please enter atleast 5 digit Password",
ConfirmPassword: "Password and Confirm Password do not match",
EmpName:"Employee Name is required"
},
}
);
function validate() {
var email = $("#emailid").val();
var emailreg = new regexp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
var valid = emailreg.test(email);
if (email == "") {
$("#div1").text("please enter an email");
}
else if(!valid)
{
$("#div1").text(" email is not valid");
}
var Phonenumber = $("#Phone").val();
var filter = /^[0-9-+]+$/;
if (!(filter.test(Phonenumber)))
{
$("#div2").text("Please enter valid Phone Number");
}
}
</script>
Now Debug the application,When the user will click on save button the form will not be submitted on server side until all the input fields are not field or input fields are having valid data.
See the image for reference:
1.As you can see some of the input fields are empty,so the user is unable to post the form on server side and getting validation messages on the browser.
2.The input fields data is not valid as we can see password and confirm password are not same so user is getting validation error and unable to submit the form.
![](http://findnerd.s3.amazonaws.com/imagedata/5566/5566.png)
0 Comment(s)