Client side instant username availability validation check

Client side instant username availability validation check

Client side validation are very common in web applications these days. One of the main reason for this is saving internet bandwidth. Each HTTP request that goes to the server, consumes a lot of data while loading the whole page containing a whole lot of CSS, JavaScript, images, etc. Instead, why not just send the small amount of data that needs to be validated and wait on the same page until it comes back?

I am sure you have used Google. If you’re saying yes to that (don’t you dare say no!), then I believe you already know what we’re talking about in this article. Google provides a unique facility to its first time sign ups. Whenever you try to sign up and are filling up your details like name, address, phone number, etc. Google will also ask you to choose a username for yourself. If you remember more keenly, Google also verifies with an instant username availability check.

This feature has an exceptional usage in today’s world. The world depends on speed. Every website and app nowadays focuses primarily on speed of access. Users do not like to wait for outputs that are being generated by the application.

That is where we have so much usage of instant username availability check. Several websites have already implemented this in one form or the other.

Now let us see the benefits of adding an instant check to the UI –

  1. Interactive user experience. Users will love to save time with this feature. They will be able to try out every possible combination they want instantly at that point. No system generated strings sent to the mail. Users will love to see their provided combinations being validated for instant availability check.
  2. Your application will be duplicate proof. Meaning, users will now be able to choose a string that is not present in the database. No more hassles of maintaining records as to whether two persons has the same username or not. Your username will also behave as a primary key along with email ID.

We will implement this feature with the help of JQuery and AJAX. One of the most beautiful and very similar article that I published was on JQueryUI autocomplete. It takes your input and shows suggestions from the database.

If you are new to AJAX and JQuery stuffs, you can have a look at the article on Retrieving data using JQuery AJAX. That is the method we are going to use here today.

Method for implementing instant username availability check

For many of you readers, AJAX post method and retrieving data through AJAX is quite a common task. So, I will not detail about those procedures here. If you are still not very sure about your knowledge in this, then do visit the links mentioned above to a get a detailed overview.

So our procedure goes like this –

  1. First of all, we will create a very basic static HTML file. This file will behave as our interface basically. The output and input can be seen here. Not much of designing. Just enough to grasp the concept.
  2. Next, we create some input fields (maybe 4 at the maximum – like name, address, email ID and username). Once that is created, we will now concentrate on the PHP and JQuery codes.

Basically the concept is, our HTML file is capturing the data with the help of a form. The form is then sending the data to a PHP file via jQuery. Before sending the data to the PHP file for saving, the data is being validated.

  1. Now, the validation here is of two types – the first validation is very basic. This validation checks whether all the fields have some value or not. Otherwise, the form will not be allowed to be submitted.

The second validation is our prime concern here – the username validation or the instant username availability check. This will quickly throw user input value to the backend, each time the user enters a new character. The control will then check whether the given string matches with some already existing string in the database.

  1. For less complications, we have omitted certain validations like validating the email field value, etc.
  2. So, the flow is simple. Instant username validation first using AJAX and JQuery to retrieve data from the database. Then, collecting all of the input field values, serializing them in jQuery and sending them to PHP for unserializing. The submit of the form is also done using the jQuery submit procedure using AJAX. So, theirs is no page reload after the form submits.
  3. The submit option is introduced so that users can add their custom usernames while testing the system, apart from the existing usernames.

Snippets linked to the procedure for instant username availability

The HTML and CSS code is simple. I have created my own design with my custom selectors. You can make any changes you feel like.

<form action="" method="post" id="form">
                    <table>
                        <tr>
                            <td><label>Username</label></td>
                            <td><input type="text" name="username" class="textinput" id="username"/></td>
                            <td><img src="img/pass.png" width="20" height="20"/></td>
                        </tr>
                        <tr>
                            <td><label>Email</label></td>
                            <td><input type="text" name="email" class="textinput" id="email"/></td>
                            <td><img src="img/pass.png" width="20" height="20"/></td>
                        </tr>
                        <tr>
                            <td><label>Name</label></td>
                            <td><input type="text" name="name" class="textinput" id="name"/></td>
                            <td><img src="img/pass.png" width="20" height="20"/></td>
                        </tr>
                        <tr>
                            <td><label>Address</label></td>
                            <td><input type="text" name="address" class="textinput" id="address"/></td>
                            <td><img src="img/pass.png" width="20" height="20"/></td>
                        </tr>
                        <tr>
                            <td colspan="2"><input type="submit" name="submit" class="buttons" id="submit" value="Sign Up"/></td>
                            <td></td>                            
                        </tr>
                    </table>                    
                </form>   

For the validation and instant username availability script, refer to the following code. The keyup event helps us fire the validation check whenever the user types in any character. Each time the value is picked up and sent to a PHP file via AJAX and JQuery GET to be checked for existing values having the same value.

$.get(
                    "check.php",
                    {value:value},
                    function(data){
                     if(data.flag==='1'){
                         //alert('user exists');
                         thiss.parent('td').siblings('td').children('img').attr('src','img/fail.png').show();
                         thiss.addClass('redColor');
                         flag=0;
                     }
                     else{
                         thiss.parent('td').siblings('td').children('img').attr('src','img/pass.png').show();
                         thiss.removeClass('redColor');
                         flag=1;
                     }
                 },
                 "json");
$value=$_GET['value'];
    
        $query2="SELECT username FROM usernames WHERE username = '$value'";

        $results2 = mysql_query($query2)
        or die(mysql_error());
          
        if(mysql_num_rows($results2)>0)
        {
            
            echo json_encode( array( "flag"=>"1" ) );
        }
        else
        {
            echo json_encode( array( "flag"=>"0" ) );
        }       

In the below code, note how I have used the jQuery submit function and controlled its flow according to the validations. The form does not submit until the flag is signaling a true value.

$('#form').submit(function(e){
        var flag2 = 0;
        e.preventDefault();
        $('.textinput').each(function(){
            if($(this).val() !== ''){
                flag2++;
            }
        });
        if(flag2 ===4 && flag===1){        
            var value = $('#form').serialize();            
            $.post(
              "submit.php",
              {value:value},
              function(data){
                  $('#form').slideUp('3500').siblings('#confirmation').html(data).show();
              }
            );
        }
        else{
            alert('Please enter the fields correctly');
        }
    });

client-side-instant-username-validation-check-jquery-ajax-2

When the code is submitted, the jQuery syntax serializes the form data before using AJAX to send it to a PHP file. There the serialized string is broken into an array and stored in the database. Once the insert is successful, the confirmation is automatically fired in the HTML file. Also, the new value will also be part of the instant username availability check from this moment onwards.

$value=  array();
    parse_str($_POST['value'], $value);
    
    $username = $value['username'];
    $name = $value['name'];
    $address = $value['address'];
    $email = $value['email'];
    
    $query="INSERT INTO usernames(username,name,address,email) 
            VALUES('".$username."','".$name."','".$address."','".$email."')";

        $results = mysql_query($query)
        or die(mysql_error());
          
        if(mysql_affected_rows()>0)
        {            
            echo "Successfully updated";
        }
        else
        {
            echo '<span style='.'"color:red"'.'>Please try again...</span>';
        }
       

Comments are closed.