views:

116

answers:

4

Hi, I want to know how can I validate using Javascript that if user has entered any username at the time of creating an account is already present in database and ask user to type any other username?

+3  A: 

The answer is AJAX. If you must validate against a database, you need to make a call to the server. The only way to do that (EDIT: properly) without reloading the page is AJAX. How you implement it will depend upon what javascript libraries you are using, if any, and what your server is like. I suggest you do a little searching and reading on it - this is a pretty common use case.

Eric Mickelsen
*The only way to do that without reloading the page is AJAX.* Well... technically AJAX isn't the only solution but it's the only worth considering.
Crozin
@Crozin: That's true. You could do something like load every username with the page or something that's just AJAX-esque, like a wacky iframe. There are an infinite number of wrong ways to do it.
Eric Mickelsen
+9  A: 
  1. Attach listener for blur event for <input /> element.
  2. Using AJAX send request to the server (with field value as parameter)
  3. On the server side check whether given username is already in use or not
  4. Based on server's response display (or not) This username is already in use message

jQuery (I'm too lazy for pure JS) + PHP sample code:

<form ...>
    ...
    <input type="text" name="username" id="input-username" />
    <p class="error"></p>
    ...

$("#input-username").blur(function() {
    $.post("/check-username.php", { username: $(this).val() }, function(data) {
        if ("0" == data) { /* username in use */
             $(this).next("p").text("This username is already in use.</p>");
        } else {           /* username is fine */
             $(this).next("p").empty();
        }
    });
});

<?php

$username = $_POST['username'];

// check whether given username exists in database
$usernameExists = ...;

echo $usernameExists ? '0' : '1'; // 0 if exists, 1 if not.
Crozin
A: 

Ajax might not be the only solution, since usernames are generally public. A simple way is to just have an RDF/XML document at some point (which just updates with every new user added) which has a list of all the users on your site that you can easily just traverse with Javascript DOM to see if that user is already in use. You also make them pay computational power, not you, depending on how nice you are it's an advantage or a dis-advantage.

Lajla
Possible, but this solution is pretty bad. That's an O(n) cost for search, a HUGE cost in bandwidth, tons of costly document updates (with resource contention), etc. By contrast, the best solution uses far less bandwidth and is faster and more efficient all around.
Eric Mickelsen
Document updates is a null argument, that XML files is obviously going to be dynamically generated each time it is requested, also, it can be used for other reasons, which is why I suggested RDF/XML, just as this page I type on is. Bandwidth is also lower than one might expect. A dedicated RDF file to house all the usernames of this community in would be about 1/4 the size in characters of what is needed to load to display this page.
Lajla
Besides having poor performance, this is actually orthogonal to whether to use AJAX. You can use either AJAX or another solution (e.g. hidden iframe) for both direct lookups (/isUsernameTaken?username=foo) or accessing an XML document (/allUserNames.xml).
Matthew Flaschen
@Lajla: Not even close. There are several times more users on SO then there are bytes in this page. If you generate the xml files dynamically every time then you're actually putting MORE load on you database, not less.
Eric Mickelsen
174 580 users by looking at the user tab.Saving this total page cost me 490 kb disk space. Well, it was 1/3 then, fairly reasonable estimate.You also put a lot less load on your database, just displaying the entire content of the 'user' cell by a while loop is going to take a lot less than actualyl querying if a certain username exists. As in, also matching against all those usernames to see if there is a character-by-character match,The fact that a lot of sites can just output a page (in HTML no less) that contains the entire userbase shows this, also, many sites have that RDF in sioc.
Lajla
@Lajla: No, it's not 490kb, it's 49kb. And if we assume about 8 characters per username (and there are more than that), the list would be well over a megabyte. And because of the way that database indexes perform, outputting one match on an indexed field can be so much faster than outputting all records. You're still way off.
Eric Mickelsen
I'm not talking about only the HTML, I'm talking about all the data needed to display the page, this includes images and scripts and what-not (a lot is cached).The simple fact is that many communities have such an RDF/XML already available, it's called sioc, check it out of you don't know it yet.Other than that, most sites do not have a six digit user number. In a lot of cases this approach is far more economical, especially because the XML/RDF can already be there on the basis of sioc.
Lajla
+1  A: 

Personally, I would use a JQuery validation plugin just to make things simple. http://bassistance.de/jquery-plugins/jquery-plugin-validation/

But in general it would consist of a small AJAX request to a server (ie. JSON object) with the username and do a 'search' in your database and return either true/false after the user hits enter or tab in the textfield (attach an event listener). Then within your callback response alter the DOM elements of your choice to indicate to your users whether the account name is already present in the database or not.

Rsyntax