Monday, October 10, 2011

JQuery: Checking for username availabity

There are many times when a user's username must be unique in order to conform to some data model constrains.  Usually there is some kind of registration form with fields such as, username, password, email, etc, that must be fill out by a new user.
Instead of waiting for the user to fill out all the information and submit the form to be validated all at once, we can use an asynchronous call to check if the the username enter by the user is available or has already been taken. The following example demonstrates this by using the JQuery framework.

<script type="text/javascript">
     
$(document).ready(function() {
           //get value entered in the input field for username
           $('#username').blur(function() {
       if ($('#username').val()) {
           checkAvailability();
       }
   });
});


function checkAvailability() {
     $("#availability_status")
           .html('<img src="
                        ${pageContext.request.contextPath}
                             /resources/images/animation/horizontal_bar.gif"
                                 align="absmiddle">&nbsp;Checking availability...');
     $.getJSON("./checkUserNameAvailability", {username : $('#username').val()},
      function(available){
          $("#availability_status").ajaxComplete(function(event, request){
          if (available) {
              $("#submit").attr("disabled", false);
              $("#availability_status").html('<img src="${pageContext.request.contextPath
                                            }/resources/images/animation/available.png" align="absmiddle">
                                                  <font color="Green"> Available </font>  ');
          } else {
              $("#submit").attr("disabled", true);
              $("#availability_status").html('<img src="${pageContext.request.contextPath}/
                                           resources/images/animation/not_available.png"  align="absmiddle">
                                             <font color="red">Not Available </font>');
                }
     });
    }
                );
      }
</script>


The check availability function checks the availability of the username entered by the user. In this case we are creating a GET request. If the username is available, a green check mark image is displayed next to the input field, otherwise a red check mark image is displayed, and the form submit button is disabled.
That's it very simple.

No comments:

Post a Comment