What is Remote Validation??
Remote validation is a Process where we post validate field data to server, without post all form data to server.
We can validate the field before post all data to server. In simple word, we have not need to click submit button to check form validation status.
Let's start with example :
We need a form for validation testing so for this visit my previous article CRUD Operation in MVC
then come here.
In my previous article we have :
In MVC, Model handle all validation related activity. So Create one class for remote validation in Model folder, class name is RemoteValidaton.cs, here we will validate three fields name, mobile number & email.
Code for RegistrationController
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using sandeepcodes.Models;// Add ref of Model
using System.Data.Entity;
namespace sandeepcodes.Controllers
{
public class RegistrationController : Controller
{
dataEntities db = new dataEntities(); // Create Connection
// GET: Registration
public ActionResult Index()
{
return View();
}
public ActionResult Insert()
{
return View();
}
[HttpPost]
public ActionResult Insert(RegistrationDetail obj)
{
if (ModelState.IsValid)
{
db.RegistrationDetails.Add(obj);
db.SaveChanges();
return RedirectToAction("Insert", "Registration");
}
else
{
return View();
}
}
//Check Duplicate Mobile No
public JsonResult mobilecheck(string MobileNo)
{
return Json(!db.RegistrationDetails.Any(x => x.MobileNo.Trim() == MobileNo.Trim()),
JsonRequestBehavior.AllowGet);
}
//Check Duplicate Email Id
public JsonResult emailcheck(string EmailID)
{
return Json(!db.RegistrationDetails.Any(x => x.EmailID.Trim() == EmailID.Trim()),
JsonRequestBehavior.AllowGet);
}
public ActionResult Details()
{
var list = db.RegistrationDetails.ToList();
return View(list);
}
public ActionResult Edit(int? id)
{
RegistrationDetail empdetails = db.RegistrationDetails.Find(id);
return View(empdetails);
}
[HttpPost]
public ActionResult Edit(RegistrationDetail obj)
{
RegistrationDetail data = db.RegistrationDetails.Find(obj.ID);
data.Name = obj.Name;
data.EmailID = obj.EmailID;
data.MobileNo = obj.MobileNo;
data.Address = obj.Address;
data.Age = obj.Age;
db.Entry(data).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Details");
}
public ActionResult Delete(int id)
{
RegistrationDetail detail = db.RegistrationDetails.Find(id);
db.RegistrationDetails.Remove(detail);
db.SaveChanges();
return RedirectToAction("Details");
}
}
}
View Page Code
Create one view page with name insert.cshtml.
In view page below mentioned scripts should be must.
Complete code are :
@model sandeepcodes.Models.RegistrationDetail
@{
ViewBag.Title = "Registration Form";
}
<h2>Insert</h2>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script> @*For remote validation*@
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>@*For remote validation*@
@using (Html.BeginForm("Insert", "Registration", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
<div>
<div style="width:300px">
@Html.LabelFor(x => x.Name)
@Html.TextBoxFor(x => x.Name, new { @class = "form-control" })
@Html.ValidationMessageFor(x => x.Name, "", new { @class = "text-danger" })
</div>
<div style="width:300px">
@Html.LabelFor(x => x.MobileNo)
@Html.TextBoxFor(x => x.MobileNo, new { @class = "form-control" })
@Html.ValidationMessageFor(x => x.MobileNo, "", new { @class = "text-danger" })
</div>
<div style="width:300px">
@Html.LabelFor(x => x.EmailID)
@Html.TextBoxFor(x => x.EmailID, new { @class = "form-control" })
@Html.ValidationMessageFor(x => x.EmailID, "", new { @class = "text-danger" })
</div>
<div style="width:300px">
@Html.LabelFor(x => x.Age)
@Html.TextBoxFor(x => x.Age, new { @class = "form-control" })
</div>
<div style="width:300px">
@Html.LabelFor(x => x.Address)
@Html.TextBoxFor(x => x.Address, new { @class = "form-control" })
</div>
<div align="left">
<br />
<input type="submit" name="save" class="btn btn-success" value="Save" />
</div>
</div>
}
Note : All highlighted content are important.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations; // Namespace for Remote validation
using sandeepcodes.Models;//Add Ref. for RegistrationDetails Class
using System.Web.Mvc;
namespace sandeepcodes.Models
{
[MetadataType(typeof(UserMetaData))]
public partial class RegistrationDetail
{
}
// Partial Class name should be same as that class name which you want to validate
public class UserMetaData
{
[Display(Name = "User name")]
[Required(ErrorMessage = "You forgot to enter a username.")]
[StringLength(12, MinimumLength = 6,
ErrorMessage = "Username must be between 6 and 12 characters.")]
public string Name { get; set; }
[Required(ErrorMessage = "Please Enter Mobile")]
[Phone]// validation type
[Display(Name = "Mobile No")]
[StringLength(10, ErrorMessage = "The Mobile must contains 10 characters",
MinimumLength = 10)]
[Remote("mobilecheck", "Registration", HttpMethod = "POST",
ErrorMessage = "Mobile no already exists.")]
public string MobileNo { get; set; }
[Display(Name = "Email")]
[RegularExpression(@"^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$",
ErrorMessage = "Please Enter Correct Email Address")]
//Remote is for the remote side validation
[Remote("emailcheck", "Registration", HttpMethod = "POST",
ErrorMessage = "Email ID already exists.")]
public string EmailID { get; set; }
}
}
Note : emailcheck & mobilecheck is Action name and Registration has contoller name.
Now build your solution & execute view page insert.cshtml.
For better understand go through once my previous article CRUD Operation in MVC then come here.
Benefits of Remote Validation
Remote validation is a Process where we post validate field data to server, without post all form data to server.
We can validate the field before post all data to server. In simple word, we have not need to click submit button to check form validation status.
Let's start with example :
We need a form for validation testing so for this visit my previous article CRUD Operation in MVC
then come here.
In my previous article we have :
- Controller : RegistrationContoller.cs
- View : Insert.cshtml, see below
- Model Class : RegistrationDetails.cs, see below
In MVC, Model handle all validation related activity. So Create one class for remote validation in Model folder, class name is RemoteValidaton.cs, here we will validate three fields name, mobile number & email.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using sandeepcodes.Models;// Add ref of Model
using System.Data.Entity;
namespace sandeepcodes.Controllers
{
public class RegistrationController : Controller
{
dataEntities db = new dataEntities(); // Create Connection
// GET: Registration
public ActionResult Index()
{
return View();
}
public ActionResult Insert()
{
return View();
}
[HttpPost]
public ActionResult Insert(RegistrationDetail obj)
{
if (ModelState.IsValid)
{
db.RegistrationDetails.Add(obj);
db.SaveChanges();
return RedirectToAction("Insert", "Registration");
}
else
{
return View();
}
}
//Check Duplicate Mobile No
public JsonResult mobilecheck(string MobileNo)
{
return Json(!db.RegistrationDetails.Any(x => x.MobileNo.Trim() == MobileNo.Trim()),
JsonRequestBehavior.AllowGet);
}
//Check Duplicate Email Id
public JsonResult emailcheck(string EmailID)
{
return Json(!db.RegistrationDetails.Any(x => x.EmailID.Trim() == EmailID.Trim()),
JsonRequestBehavior.AllowGet);
}
public ActionResult Details()
{
var list = db.RegistrationDetails.ToList();
return View(list);
}
public ActionResult Edit(int? id)
{
RegistrationDetail empdetails = db.RegistrationDetails.Find(id);
return View(empdetails);
}
[HttpPost]
public ActionResult Edit(RegistrationDetail obj)
{
RegistrationDetail data = db.RegistrationDetails.Find(obj.ID);
data.Name = obj.Name;
data.EmailID = obj.EmailID;
data.MobileNo = obj.MobileNo;
data.Address = obj.Address;
data.Age = obj.Age;
db.Entry(data).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Details");
}
public ActionResult Delete(int id)
{
RegistrationDetail detail = db.RegistrationDetails.Find(id);
db.RegistrationDetails.Remove(detail);
db.SaveChanges();
return RedirectToAction("Details");
}
}
}
View Page Code
Create one view page with name insert.cshtml.
In view page below mentioned scripts should be must.
Complete code are :
@model sandeepcodes.Models.RegistrationDetail
@{
ViewBag.Title = "Registration Form";
}
<h2>Insert</h2>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script> @*For remote validation*@
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>@*For remote validation*@
@using (Html.BeginForm("Insert", "Registration", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
<div>
<div style="width:300px">
@Html.LabelFor(x => x.Name)
@Html.TextBoxFor(x => x.Name, new { @class = "form-control" })
@Html.ValidationMessageFor(x => x.Name, "", new { @class = "text-danger" })
</div>
<div style="width:300px">
@Html.LabelFor(x => x.MobileNo)
@Html.TextBoxFor(x => x.MobileNo, new { @class = "form-control" })
@Html.ValidationMessageFor(x => x.MobileNo, "", new { @class = "text-danger" })
</div>
<div style="width:300px">
@Html.LabelFor(x => x.EmailID)
@Html.TextBoxFor(x => x.EmailID, new { @class = "form-control" })
@Html.ValidationMessageFor(x => x.EmailID, "", new { @class = "text-danger" })
</div>
<div style="width:300px">
@Html.LabelFor(x => x.Age)
@Html.TextBoxFor(x => x.Age, new { @class = "form-control" })
</div>
<div style="width:300px">
@Html.LabelFor(x => x.Address)
@Html.TextBoxFor(x => x.Address, new { @class = "form-control" })
</div>
<div align="left">
<br />
<input type="submit" name="save" class="btn btn-success" value="Save" />
</div>
</div>
}
Note : All highlighted content are important.
- Insert is Action name
- Registration is Controller name
- ValidationMessage, return the validation status
- If above mentioned scripts are not exist in your scripts folder then goto Manage NuGet Packages for solution and find all scripts and install it. Without these scripts remote validation will not work.
Code for RemoteValidation.cs page
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations; // Namespace for Remote validation
using sandeepcodes.Models;//Add Ref. for RegistrationDetails Class
using System.Web.Mvc;
namespace sandeepcodes.Models
{
[MetadataType(typeof(UserMetaData))]
public partial class RegistrationDetail
{
}
// Partial Class name should be same as that class name which you want to validate
public class UserMetaData
{
[Display(Name = "User name")]
[Required(ErrorMessage = "You forgot to enter a username.")]
[StringLength(12, MinimumLength = 6,
ErrorMessage = "Username must be between 6 and 12 characters.")]
public string Name { get; set; }
[Required(ErrorMessage = "Please Enter Mobile")]
[Phone]// validation type
[Display(Name = "Mobile No")]
[StringLength(10, ErrorMessage = "The Mobile must contains 10 characters",
MinimumLength = 10)]
[Remote("mobilecheck", "Registration", HttpMethod = "POST",
ErrorMessage = "Mobile no already exists.")]
public string MobileNo { get; set; }
[Display(Name = "Email")]
[RegularExpression(@"^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$",
ErrorMessage = "Please Enter Correct Email Address")]
//Remote is for the remote side validation
[Remote("emailcheck", "Registration", HttpMethod = "POST",
ErrorMessage = "Email ID already exists.")]
public string EmailID { get; set; }
}
}
Note : emailcheck & mobilecheck is Action name and Registration has contoller name.
Now build your solution & execute view page insert.cshtml.
For better understand go through once my previous article CRUD Operation in MVC then come here.
Benefits of Remote Validation
- Time saving
- Fast speed
- Don't need to wait post entire form to server, you can check validate filed on tab changed.