Check and Validate Username in jQuery

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
$host = "localhost";
$db_name = "your_db_name";
$username = "your_db_username";
$password = "your_db_password";
 
//connect to mysql server
$mysqli = new mysqli($host, $username, $password, $db_name);
 
//check if any connection error was encountered
if(mysqli_connect_errno()) {
    echo "Error: Could not connect to database.";
    exit;
}
?>

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>
    </head>
<body>
 
<p>
    <div id = "feedback"></div>
    <form name = 'form'>
        <input type = 'text' id = 'username_input' name = 'username' >
    </form>(try 'johnny', 'albert', 'chris' or 'james')
</p>
 
<div class='back-link'>
    <a href='https://www.codeofaninja.com/2011/06/check-and-validate-username-without.html'>Back to tutorial page</a>
</div>
 
<script type = "text/javascript" src = "js/jQuery.js"></script>
<script type = "text/javascript">
 
    // when the document is ready, run the jquery script
    $(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(){
 
            $.post('check.php', { username: form.username.value },
                function(result){
                    $('#feedback').html(result).show();
                });
 
        });
    });
</script>
 
</body>
</html>

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

<?php
include_once("config_open_db.php");
 
isset( $_POST['username'] ) ? $username = $username = $mysqli->real_escape_string( $_POST['username'] ) : $username = "";
if($username == null){
    echo "Please enter a username.";
}
 
elseif(strlen($username) < 5){
    echo "Username is too short.";
}
 
else{
    $sql = "SELECT *
            FROM users
            WHERE username = \"{$username}\"";
 
    $result = $mysqli->query($sql);
    $num = mysqli_num_rows($result);
    if($num == 1 ){
        while($row = mysqli_fetch_array($result)){
            $fn = $row['firstname'];
            $ln = $row['lastname'];
            echo "<div style='color: red; font-weight: bold;'>Username already taken.</div>";
        }
    }else{
        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!
[purchase_link id="12309" text="Download Now" style="button" color="green"]

Related Tutorials

We listed all our high quality full-stack web development tutorials here: Click here.

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

Hi! I'm Mike Dalisay, the co-founder of codeofaninja.com, a site that helps you build web applications with PHP and JavaScript. Need support? Comment below or contact [email protected]

I'm also passionate about technology and enjoy sharing my experience and learnings online. Connect with me on LinkedIn, Twitter, Facebook, and Instagram.