Home jQuery

Check and Validate Username in jQuery

jquery-tutorial

Hi there developer! Today we are going to do a code snippet that:

  1. Checks if a username is available or not (in the database).
  2. If the username is available, the program will output “[your_username] is available!”
  3. Then if it is not available, “Username already taken” will be printed.
  4. This code also has a simple validation that states whether the inputted username is too short or is empty.

All those tasks will be performed via AJAX, so it is without page refresh. You can expand its validation though.

In this code, we need a sample data from the database table and four (4) files which includes: config_open_db.php, index.php, check.php and the jQuery library file.

database – you could have this table structure and data:

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `firstname` varchar(32) NOT NULL,
  `lastname` varchar(32) NOT NULL,
  `username` varchar(32) NOT NULL,
  `password` varchar(32) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

--
-- Dumping data for table `users`
--

INSERT INTO `users` (`id`, `firstname`, `lastname`, `username`, `password`) VALUES
(1, 'John', 'Doe', 'johnny', 'john'),
(2, 'Albert', 'Minston', 'albert', 'albert');

config_open_db.php – this file is for database connection so that we’ll be able to load usernames from the database. You should have something like this: (Please supply the variables with YOUR settings.)

<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'codeofaninja'; 

$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
mysql_select_db($dbname) or die ('Unable to select  database!');
?>

index.php – this file makes our user interface for this tutorial. jQuery library is of course included in this file.

<html>
    <head>
    <title>Username checker and validator</title>
    <script type = "text/javascript" src = "js/jQuery.js">
    </script>
    <style type = "text/css">
        #feedback{
            line-height:
        }
    </style>  
    
<script type = "text/javascript">
    //this script will be triggered once the 
    //user type in the textbox 

    //when the document is ready, run the function
    $(document).ready(function(){ 
        $('#feedback').load('check.php').show();
        //we use keyup so that everytime the 
        //user type in the keyboard, it'll check
        //the database and get results
        //however, you can change this to a button click
        //which is I think, more advisable. 
        //Sometimes, your server response is slow
        //but just for this demo, we'll use 'keyup' 
        $('#username_input').keyup(function(){
            //this will pass the form input
            $.post('check.php', { username: form.username.value },
            //then print the result
            function(result){
                $('#feedback').html(result).show();
            });
        });
    });
</script>

    </head>
<body>
    <p>
        <form name = 'form'>
            <input type = 'text' id = 'username_input' name = 'username' >
        </form>
        <div id = "feedback">
            <!-- the result will be shown here -->
        </div>
    </p>
</body>
</html>

check.php – this file makes the request to the database, to check the inputted value.

<?php
include_once("config_open_db.php");
//define posted value
$username = isset( $_POST['username'] ) ? mysql_real_escape_string( $_POST['username'] ) : "";

if($username == null){
    //if no user input
    echo "Please enter a username.";
}elseif(strlen( $username ) < 5){
    //if the input is less than 5 characters
    //we used 'strlen' function to count string characters
    echo "Username is too short.";
}else{
    //query the inputted value
    $sql = "select  * from users where username = '$username'";

    $rs = mysql_query( $sql );
    $num = mysql_num_rows( $rs );

    if($num == 1 ){ //if username found
        while($row = mysql_fetch_array( $rs )){
            $fn = $row['firstname'];
            $ln = $row['lastname'];
            echo "<div style='color: red; font-weight: bold;'>Username already taken.</div>";
        }
    }else{ //if username not found
        echo "<span style='font-weight: bold;'>$username</span> is available!";
    }
}
?>

Download jQuery Code Examples

You can download all the code used in this tutorial for only $9.99 $5.55!

Thank you for learning from our post about Check and Validate Username in jQuery.