Remote Validation In MVC

Hi everyone. Today, we are going to see an amazing feature of ASP.NET MVC Framework, i.e. Remote Validation. This feature of MVC allows you to perform client-side validation with a Server side callback. This attribute is in System.Web.Mvc namespace. The best part of this attribute is it does not send a whole form or all the elements to the Server; it sends only the specific field, where remoting attribute is decorated on a property.

Let’s take a real time example. Here, I have a project in which we are doing registration. In this registration, the user can login through an Email and a password. The Email ID cannot be a duplicate field in a database.

Real explanation

Let's create an application. In my application, I have a model with the name RegistrationModel and the detail of it is given below.

Model

  1. public class RegistrationModel  
  2.     {  
  3.         [Required]  
  4.         public string FirstName { get; set; }  
  5.       
  6.         [Required]  
  7.         public string LastName { get; set; }  
  8.   
  9.   
  10.         [Required]  
  11.         [EmailAddress]  
  12.         [Remote("IsEmailExist""UserRegistration", ErrorMessage = "Email already exists!")]  
  13.         public string Email { get; set; }  
  14.          
  15.           
  16.         public string Password { get; set; }  
  17.     }  

Hence, let’s elaborate the remote attribute.


The first blue underlined part is the name of the Action. In the control, it will go to validate the field at the Server side and the second one is the controller name, and this action will return Boolean value if it's returned.

The code is given below in which I have my Action named: IsEmailExist.

CONTROLLER:ACTION

  1. public JsonResult IsEmailExist(string Email) {  
  2.     return Json(!_db.Registrations.Any(x => x.Email == Email), JsonRequestBehavior.AllowGet);  
  3. }  

As soon as the user enters an Email in the field; the control will come over to the action and in a parameter, it will get the details of an Email Id entered by the user. Afterwards, it will check in the database, whether the E-mail exists or not, as per the condition and it will return the Boolean value.

HTML side

There are no changes in view and it's the same as TextBoxFor HTML attribute and validation message.


Let's check the result for the same.

Record saved for the first time shows No Error.


 When we try to enter the same, an Email it will give an error.


Here, we are doing validation on a single condition. For example, we are just checking whether the user’s email exists in the database or not, if we want to do validation with the multiple fields like an email.


I hope, this article will help you. Thank you very much for reading this blog.

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now