I was reading Nettuts.com this week and saw the post by Matt Vickers on checking the availability of a username with Mootools. I tend not to use Mootools so i thought I’d replicate the technique using jQuery. The code degrades gracefully if JavaScript is disabled, it is advised that you always check the username against the database again, just before you add any data to the database.

Its worth noting that because were checking the username against the database on keyUp we’re making a unique request each time. To help limit these requests we check that the username is more than 4 characters before perfoming an ajax request.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script>
$(document).ready(function(){
$('#username').keyup(username_check);
});
function username_check(){
var username = $('#username').val();
if(username == "" || username.length < 4){
$('#username').css('border', '3px #CCC solid');
$('#tick').hide();
}else{
jQuery.ajax({
type: "POST",
url: "check.php",
data: 'username='+ username,
cache: false,
success: function(response){
if(response == 1){
$('#username').css('border', '3px #C33 solid');
$('#tick').hide();
$('#cross').fadeIn();
}else{
$('#username').css('border', '3px #090 solid');
$('#cross').hide();
$('#tick').fadeIn();
}
}
});
}
}
</script>
This is the code that checks the database to see if the username exists or not. dbConnector.php is the database connection class that i use in all my projects and is in the download of the project files.
The first thing we do is trim any white space and convert the string to lowercase. i’ve ensured that the usernames in the database are all lowercase. So the usernames aren’t case sensitive when a user types one in to the box.
IMPORTANT! because we’re handling unknown user generated data we have to use the mysql_escape_string() function to stop SQL injection and to strip any unwanted chars
Notice that i have omitted the last php tag. If a page contains only PHP code, best practice is to omit the PHP end tag ( ?> ). PHP does not require the end tag in PHP only pages.
Including the end tag can cause unwanted injection of trailing white spaces which can cause header already sent errors.
<?php include("dbConnector.php"); $connector = new DbConnector(); $username = trim(strtolower($_POST['username'])); $username = mysql_escape_string($username); $query = "SELECT username FROM usernameCheck WHERE username = '$username' LIMIT 1"; $result = $connector->query($query); $num = mysql_num_rows($result); echo $num; mysql_close();
Here’s the input form field and the two images.
Username: <input name="username" id="username" type="text" /> <img id="tick" src="tick.png" width="16" height="16"/> <img id="cross" src="cross.png" width="16" height="16"/>
Here’s the basic style to format the username input field, and to hide the tick and cross image.
#username{
padding:3px;
font-size:18px;
border:3px #CCC solid;
}
#tick{display:none}
#cross{display:none}
This entry was posted in Javascript, PHP, Tutorials, featured, jQuery and tagged Ajax, Javascript, jQuery, PHP, Tutorials. Bookmark the permalink.
It’s always a pleasure coming to this site and learn something. Keep it up Ashley.
Wow… I liked it so much. Simple and easy to use, but I think make Ajax requests in each letter typed by user is not so good, even after 4 letters, I prefer use in onblur event or even in submit form.
mysql_escape_string is a nice tip and we can’t forget about use it. Another cool thing I didn’t know is omit the PHP end tag is a best practice.
Thanks a lot! Cheers!
Thank you very much, much better than my current way of checking
Thanks might be helpful in my future projects
I’m definitely gonna use this one! Thanks!
Great tutorial! This complete newbie was able to implement it on a new project, thank you so much!
Pingback: Servefault.com
Great work. Could you show how to use with asp?
The work around could be to use PHP. Can you show me how to connect to an Access database using check.php?
Hi Ashley,
Done it! ASP code to connect to DB.
<%
Dim rsUser__MMColParam
rsUser__MMColParam = "1"
If (Request.Form("username") “”) Then
rsUser__MMColParam = Request.Form(“username”)
End If
%>
1
Hi Ashley, thanks for this tutorial, i’ts work on my project
..
But how about with the submit button? If the username unavailabe, I was able to process the form. Does anyone can help?
nice tutorial! sir thanks!!!!!1
Hi Ashley,
Nice article!!!
How can i use other events like onblur instead of keyup
Great write-up, thanks for sharing. I already put it to good use and I’d like to add a tiny performance issue that I came across – and fixed:
Sometimes, when you type very fast, and it switches the cross for the checkmark or vice-versa, it liked to “skip” to hide() the old icon for me, and I ended up having both icons showing next to each other. I’m assuming this can happen when the routines overlap, especially when you add in more than just hide() and fadeIn() like I did. For example, I am also filling a nice message into a notice box with html() before I call hide() and fadeIn().
To fix this, I simply added the fadeIn() inside of a function of hide(). My logic was that when it ges reduced to a single function, it’s less likely that it gets skipped when you type fast. It works so far for me.
On line 25 of your above code, you have
$('#tick').hide();
$('#cross').fadeIn();
…and I changed that to
$('#tick').hide(100, function() {
$(this).parent().find('#cross').fadeIn(400);
});
Same for the ELSE part.
It’s only a minor thing but I hope it helps. Thanks again Ashley for your great post!
hey Ashley, good stuff man.. i just came across your site and its very useful … keep it up
How do you check the usernames? What if I want to fill an array with names and check against it?
Sometimes, when you type very fast, and it switches the cross for the checkmark or vice-versa, it liked to “skip” to hide() the old icon for me, and I ended up having both icons showing next to each other. I’m assuming this can happen when the routines overlap, especially when you add in more than just hide() and fadeIn() like I did. For example, I am also filling a nice message into a notice box with html() before I call hide() and fadeIn().
+1
I can’t retrieve a set usernames from my database. how can i do it with the php page?where should i change?? Can you help me Ashley??
thanx in advance
Sometimes, when you type very fast, and it switches the cross for the checkmark or vice-versa, it liked to “skip” to hide() the old icon for me, and I ended up having both icons showing next to each other. I’m assuming this can happen when the routines overlap, especially when you add in more than just hide() and fadeIn() like I did. For example, I am also filling a nice message into a notice box with html() before I call hide() and fadeIn().+1
+1
Excellent, I tried it and it worked like a charm. I`m into a lot of programming for the company I work for.
Hi,
I want to check if an email exists. I have used this on the email field but if you put an incomplete email it will accept it and show a green tick and border.
I just recently implemented what you showed here in your blog. It is very affective. I wanted to offer another bit of feedback on how to slow some of the hit on the server (if your validating by email address). If your validating by email address then you can validate on valid email address. Meaning along with 4 characters, if you also check to make sure it’s a valid email BEFORE hitting the server it’ll restrict some of the flow to the server. However you can only do that if it’s a email address that’s being used as the username (which ends up happening a lot, at least in the systems I build).
Either way it was a great idea and a very nice/clear implementation.
—–
http://www.infotechnologist.biz
http://www.realmofwriting.com
Subscribe to all the Papermashup Tutorials and articles straight to your RSS reader.
Sign up and get all the Papermashup tutorials straight to your inbox.
Follow us on Twitter and get in-stream messages
27 discussions around jQuery PHP & MySQL Username Availability Checker