Implementing Remote Validation In MVC 5 Using Remote Attribute

Implementing Remote Validation In MVC 5 Using Remote Attribute

Remote validation utilizes to make server calls to validate data. without posting the entire form to the server when server-side validation is desirable to the client-side. It’s everything done by setting up a model and controller which is pretty neat.

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

Problem Statement

create razor view page

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

razor view list of records

How to apply validation utilizing Remove Attribute

At the point when a user gives a user name which as of now exists, the related validation error message display as below,

remote validation in asp.net mvc

Steps to follow,

Create a table

CREATE TABLE [dbo].[User] (  
   [Id] INT NOT NULL,  
   [UserName] VARCHAR (50) NOT NULL,  
   [Password] NCHAR (10) NOT NULL,  
   PRIMARY KEY CLUSTERED ([Id] ASC)  
);

Create an empty MVC project, and after that include ado.net Entity model utilizing the table User. Then build the solution.

Add UsersController with following settings,

ControllerName : UsersController
Model Class: User
Data Context Class: MyDbContext
View: Razor

Let’s put the below function into UsersController. This method will use to perform the validation. An ajax request call by this method. If this method returns true, validation succeeds, else validation failed and the structure keeps from being submitted. The user name should match the field name on the view.

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

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

using System.ComponentModel.DataAnnotations;  
using System.Web.Mvc;  
namespace MvcRemoteValidation.Models {  
    [MetadataType(typeof(UserMetaData))]  
    public partial class User {}  
    public class UserMetaData {  
        [Remote("IsUserNameAvailable", "Users", ErrorMessage = "User Already Available")]  
        public string UserName {  
            get;  
            set;  
        }  
    }  
}

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

The 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

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

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

Css also can be referenced

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

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

Unobtrusive JavaScript Validation

One of the more helpful things MVC includes is Unobtrusive Validation. with the use of the jQuery Validate module and the Unobtrusive library. The lightweight library enables us to add validation to our MVC views with no extra client-side coding. so, we use attributes like RangeAttribute and RequiredAttribute. after that include the correct script files.

Enable and Disable Client-Side Validation at Application Level

Here, We can enable or disable the client-side validation by setting the values of UnobtrusiveJavaScriptEnabled and ClientValidationEnabled keys true or false. This setting connects to the application level.


<appSettings>  
   <addkey="ClientValidationEnabled"value="true"/>  
   <addkey="UnobtrusiveJavaScriptEnabled"value="true"/>  
</appSettings>

So, in this feature can be enabled or disabled in Application_Start() in Global.asax.cs file.

Leave a Reply

Your email address will not be published. Required fields are marked *