RemoteValidation Attribute in ASP.NET MVC

One great feature we have in ASP.NET MVC is ability to do client side validations using Data Annotations and it definitely save a lot of time from writing mundane client side scripts for validations such as required, number formats, email formats etc. When we decorate properties with validation attributes, the runtime will inject JavaScript automatically when the page is rendered to do that validation. But in some scenarios we will need to do the validation in the server side say in cases such as we need to verify an user exists or not when the data is entered in the text box. Most of us will invoke an ajax call on the blur event to achieve this, but in MVC there is validation attribute that can do this for you with minimal amount of code.

Remote Validation Attribute

Remote Validation is the process in which we perform the validation in the server side for a specific control without posting the entire form information to the server. In ASP.NET MVC, we will use the Remote attribute in the System.Web.MVC namespace to the decorate the property. Let's take an example wherein we need to validate an username exists or not when he type it in the form field.

Step 1 : Decorate the property

Decorate the property with the Remote attribute with first param being the action name that needs to be executed, second one is the controller name and third is the message that needs to be shown when validation fails.

using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

public class User
{
[Required]
[Display(Name = "Enter Username")]
[Remote("CheckExistingUser", "User", ErrorMessage = "Username already exists!")]
public string UserName { get; set; }
}

Step 2 : Create the Action Method and Validation Logic

Now you need to create the action method in the controller which specified in the attribute. Here I have created a method for validating the username which will return a false if the text entered in the field is admin or administrator.

public ActionResult CheckExistingUser(string UserName)
{
     try
     {
          return Json(ValidateUser(UserName), JsonRequestBehavior.AllowGet);
     }
     catch (Exception ex)
     {
          return Json(false, JsonRequestBehavior.AllowGet);
     }
}

private bool ValidateUser(String UserName)
{
	if (UserName.ToLower().Equals("admin") || UserName.ToLower().Equals("administrator"))
        	return false;
        else
		return true;
}

Step 3 : Create the View

In the view I placed the field for the Username property and wired a method for the click event for creating the user as shown below.

@model RemoteValidation.Models.User

@using (Html.BeginForm())
{
    <div class="form-group">
        @Html.LabelFor(m => m.UserName)
        @Html.TextBoxFor(model => model.UserName, new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.UserName)
    </div>
				
    <button type="button" class="btn btn-success submit">Submit</button>
}
<div id="result"></div>
<script>
    $(function () {
        $('.submit').click(function () {
            if ($('form').valid()) {
                $.ajax({
                    url: '@Url.RouteUrl(new { action = "CreateUser", controller = "User" })',
                    data: { UserName: $('#UserName').val() },
                    type: 'POST',
                    dataType: 'json',
                    contentType: "application/json; charset=utf-8",
                    success: function (resp) {
                        $('#result').html(resp);
                    }
                });
            }
            else {
                closeAlert();
            }
        });
    });
</script>

Code in Action

Now if you run the application and enter admin in the text box, you will get the already exists error in browser just like other validation attributes. If you look in the console you can see that the remote call is being made

Note :

Please make sure that jQuery Unobtrusive validation is enabled in the site. Also it's a best practice to do the same validation in the post method too to ensure the integrity of the data as shown below

public ActionResult CreateUser(string UserName)
{
    if (ValidateUser(UserName))
        return Json(false, JsonRequestBehavior.AllowGet);
    return Json("Added User", JsonRequestBehavior.AllowGet);
}

No Comments

Add a Comment

Recent Posts