Wednesday, March 25, 2009

How to: Check login name availability in ASP.NET MVC using jQuery Validation plug-in



I need to write comments for the below code, bcoz of lack of time i am posting only abstract things,if you want to know something, write comment, i will reply.


HTML login control

< input type="text" name="txtUserName" id="txtUserName" class="textBoxes" />


jQuery Rule: Add the below rule into script tag in header & add reference to jquery-1.2.6.js,jquery.validate.js in Head Element

 
$(document).ready(function() {

         $("#frmSelfRegister").validate({
             rules: {
   txtUserName:
                     {
                         required: true,
                         remote: { type: "post", 
                                   url: "Register/IsLoginAvailable" }
                    },
    messages:{

txtUserName: { required: "User Name is Required.",
                                remote: jQuery.format("{0} is not available.")}
     }
   });
     });


The above validation code executed when the focus changes from txtUserName to some other, it will call IsLoginAvailable method available in the RegisterController, as specified in the url.




Controller Code :

Below code is the one which checks for availability of a username & returns the status to above jQuery Method. The following methods return type is JsonResult because remote method of jQuery accepts the JsonResult object only.

        
[AcceptVerbs(HttpVerbs.Post)]
        public JsonResult IsLoginAvailable(FormCollection collection)
            {
                JsonResult result = new JsonResult();

                try
                {
                       ilogIn.Text = this.GetLoginByUsername(collection.Get("txtUserName").ToString().Trim());
                       
                }
                catch (Exception ex)
                {
                    Helper.ErrLogger(ex.Message);
                }

                if (ilogIn.Text == collection.Get("txtUserName").ToString())
                {
                    result.Data = false;
                }
                else
                {
                    result.Data = true;
                    
                }
                return result;
            }

No comments: