Remote Validation in MVC3


Recently I created a MVC App in which I used data annotations for my model elements .. For eg lets have a look at my Registration Model.

public class RegistrationModel
    {
        [Required]
        [Display(Name = "User name")]
        [Remote("UserNameExists", "Account")]
        public string UserName { get; set; }

        [DataType(DataType.Password)]
        [Required]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [Required]
        [Display(Name = "Email address")]
        [DataType(DataType.EmailAddress)]
        public string EmailAddress { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do     not match.")]
        public string ConfirmPassword { get; set; }
    }

Here you see we have Data Annotations used for Username,Password,EmailAddress and confirmpassword properties.Consider Remote validation option which I used for validating a Username and display me a error message when I enter a username which is already there in my database.

[Remote("UserNameExists", "Account")]

Here the  word “UserNameExists” indicates a method which I have created in the “Accounts” controller

Lets go into the method which is as follows
public  JsonResult UserNameExists(string UserName)
        {
            List<string> usernames = new List<string>();

            foreach (MembershipUser user in Membership.GetAllUsers())
            {
                usernames.Add(user.UserName);     
            }

            if (usernames.Contains(UserName))
            {
                return Json("The Username has been taken.Please use a Different User Name", JsonRequestBehavior.AllowGet);

            }
            return Json(true, JsonRequestBehavior.AllowGet);
         
        }

So this method will check to see if the username I enter in my form exists in my database? If so show me the error message as The Username has been taken.Please use a Different User Name

NOTE:
1.Make sure to add this in your webconfig
<appSettings>

    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
    <add key="ClientValidationEnabled" value="true"/>
  
  </appSettings>
2. Also make sure to add link to Jquery in your layout_cshtml ,since Remote validation uses Jquery
<script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>

No comments:

Post a Comment