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
- public class RegistrationModel
- {
- [Required]
- public string FirstName { get; set; }
-
- [Required]
- public string LastName { get; set; }
-
-
- [Required]
- [EmailAddress]
- [Remote("IsEmailExist", "UserRegistration", ErrorMessage = "Email already exists!")]
- public string Email { get; set; }
-
-
- public string Password { get; set; }
- }
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
- public JsonResult IsEmailExist(string Email) {
- return Json(!_db.Registrations.Any(x => x.Email == Email), JsonRequestBehavior.AllowGet);
- }
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.