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 the client side. It's all done by setting up a 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, the 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
- 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 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 by 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.
- 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 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.
- <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,
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 the application level,
- <appSettings>
- <addkey="ClientValidationEnabled"value="true"/>
- <addkey="UnobtrusiveJavaScriptEnabled"value="true"/>
- </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.
References: