Remote Validation In MVC 5 Using Remote Attribute

Remote validation is an Ajax call which approves the client's information. This can undoubtedly be proficient without using ASP.NET MVC 5

Remote validation is used to make server calls to validate data without posting the entire form to the server when server side validation is preferable to client side. It's all done by setting up model and controller which is pretty neat.

Suppose if any field in a database table must be unique, and we want to check this uniqueness on the client side (after text change of text-boxes) instead of posting the whole page. 

Problem Statement

 
 
Assume that I have a user registration screen without validation. But to register a user, we need a unique User Name. If we are not applying any validation on UserName control, username would be redundant in the database. Please find the below screen which will give us an idea of how the redundant user names would be stored in the db, if there is no validation:
 

How to apply validation using Remove Attribute to resolve this issue?

When a user provides a user name which already exists, the associated validation error message should be displayed as below,

Steps to follow,
 

Create a table

  1. CREATE TABLE [dbo].[User] (  
  2.    [Id] INT NOT NULL,  
  3.    [UserName] VARCHAR (50) NOT NULL,  
  4.    [PasswordNCHAR (10) NOT NULL,  
  5.    PRIMARY KEY CLUSTERED ([Id] ASC)  
  6. );  

Create an empty MVC project, and then add an ado.net Entity model using the table User. Then build the solution. 

Add UsersController with following settings,

  • ControllerName : UsersController
  • Template



  • Model Class : User



  • Data Context Class : TestEntities
  • View : Razor

Copy and paste the below function into UsersController. This method will be used to perform the validation. An ajax request is triggered to this method. If this method returns true, validation succeeds, else validation failed and the form is prevented from being submitted. The parameter name (UserName) should match the field name on the view.

  1. public JsonResult IsUserNameAvailable(string UserName)  
  2. {  
  3.    return Json(!db.Users.Any(u => u.UserName == UserName), JsonRequestBehavior.AllowGet);  
  4. }  

Add another class under the model folder and copy paste the below code.

  1. using System.ComponentModel.DataAnnotations;  
  2. using System.Web.Mvc;  
  3. namespace MvcRemoteValidation.Models {  
  4.     [MetadataType(typeof(UserMetaData))]  
  5.     public partial class User {}  
  6.     public class UserMetaData {  
  7.         [Remote("IsUserNameAvailable""Users", ErrorMessage = "User Already Available")]  
  8.         public string UserName {  
  9.             get;  
  10.             set;  
  11.         }  
  12.     }  
  13. }  

System.Web.Mvc needs to be added as reference to add Remote attribute.

Parameters which need to be added when decorating a property with Remote attribute.

  • IsUserNameAVailable – this is the method which will get invoked
  • Users - controller where the above method belongs
  • ErrorMessage - if validation failed, this message will be displayed

Include the below references in  Create.cshtml file. jQuery, jquery.validate and jquery.validate.unobtrusive script files are required for remote validation to work.

  1. <script src="~/Scripts/jquery-1.10.2.min.js"></script>  
  2. <script src="~/Scripts/jquery.validate.min.js"></script>  
  3. <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>  
 

Css also can be referenced

  1. <linkhref="~/Content/Site.css"rel="stylesheet"/> 

Make sure ClientValidation and UnobtrusiveJavaScript are enabled in web.config,

Unobstrusive JavaScript Validation

One of the more useful things MVC includes is Unobtrusive Validation with the usage of the jQuery Validate plugin and the Unobtrusive library. This lightweight library allows us to add validation to our MVC views without any additional client-side coding; we only have to use attributes like RequiredAttribute and RangeAttribute and include the correct script files.

Enabling and Disabling Client-Side Validation at Application Level

 
We can enable and disable the client-side validation by setting the values of ClientValidationEnabled & UnobtrusiveJavaScriptEnabled keys true or false. This setting will be applied to application level,
  1. <appSettings>  
  2.    <addkey="ClientValidationEnabled"value="true"/>  
  3.    <addkey="UnobtrusiveJavaScriptEnabled"value="true"/>  
  4. </appSettings>   
Is it possible to turn these features on or off using code?
 
Yes, this feature can be enabled or disabled in Application_Start() in Global.asax.cs file.
 
Thanks for reading this tutorial.