简体   繁体   中英

How to validate username using Javascript?

我想知道如何使用Javascript验证用户在创建帐户时输入的任何用户名是否已经存在于数据库中,并要求用户键入其他任何用户名?

  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.

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM