Thursday 3 July 2014

Checking for existing username without page refresh in ASP.NET MVC (Remote validation)

In this article, we are going to learn a frequently used functionality in any web application where at the time of registration it is checked for the existing username in the database and user is alerted that this username already exists. There are few ways to do that and one of them is by using the Remote Validation in ASP.NET MVC. This article describes how to use Remote Validations in ASP.NET MVC to achieve this task.


Introduction


Remote Validation is a nice validation feature available in ASP.NET MVC. It is client side validation technique that invokes action method on the server to perform validation for a particular data.

This validation is completely different from the normal model validation where all the properties of the model is validated. In this type of validation, only a specific model property is validated. As part of this process, an AJAX request is made to the server to validate the data that has been requested. If it exists, a validation error is shown to the user. All this happens in the background, user doesn't have to click any button to perform this validation. As and when user keeps typing, this validation is performed and result is shown to the user.

Add caption



How to achieve Remote Validation?

To achieve Remote Validation, we need to do a few changes in our Model class. Below is my changed model class.
 
public class PersonalDetail
    {
        [Key]
        [DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
        public int AutoId { get; set; }
        [StringLength(20, MinimumLength = 4, ErrorMessage = "Must be at least 4 characters long.")]
        [Remote("CheckForDuplication", "Validation")]
        public string FirstName { get; set; }
        
        public int Age { get; set; }
    }
 
Notice the FirstName property and its attributes (Please note that despite my Property name is FirstName, I am treating it as UserName to bring it to this context).
 The first attribute is to specify the maximum and minimum number of 
characters accepted in this field and the second attribute is the one we
 are talking about here. This specifies that Remote validation will be 
performed on this field and its parameter specifies that which action 
method of which controller will be used to generate URL to be called 
from JavaScript validation library.
 
 
 


My view page (.cshtml) code looks like this, there is no major changes in this because of Remote Validation.

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>PersonalDetail</legend>

        <div class="editor-label">
            Username
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.FirstName)
            @Html.ValidationMessageFor(model => model.FirstName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Age)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Age)
            @Html.ValidationMessageFor(model => model.Age)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
In the Controller, we have following methods
        public ActionResult RemoteValidation(PersonalDetail pd)
        {
            return View(pd);
        }

        public JsonResult CheckForDuplication(string FirstName)
        {
            var data = db.PersonalDetails.Where(p => p.FirstName.Equals(FirstName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();

            if (data != null)
            {
                return Json("Sorry, this name already exists", JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(true, JsonRequestBehavior.AllowGet); 
            }
        }
The first method simply, returns the RemoteValidation view with my model.

The second method gets called when user starts writing characters in the UserName text box (in my case the model property name is FirstName but I am calling this as UserName). However this method is not get called unless user enters 4 characters, this happens because of StringLength attribute on this field.


When user writes at least 4 characters, the second method gets called and in this method we are validating the FirstName in the database and if it exists; returning the error message.


If the UserName (in my case FirstName field of the database) doesn't exists, second method returns true and the validation passes.


Note that all these steps are performed using jQuery AJAX and no complete post back request is sent to the server so all these processes looks very smooth and interactive.

Conclusion

Remote Validation helps us giving quick feedback to the user for the availability of UserName (in this case FirstName) however it should be used cautiously as every key stroke in the UserName textbox after 4 characters will call the Validation method causing consumption of more bandwidth and resources of the server.

Hope this article was useful. 

Thanks for reading. Do share your comment or feedback.
 
 

No comments :