Jump to content

Username validations in php and ajax


sunilpaladugu

Recommended Posts

You could validate the username using preg_match, something like.

 

$username = $_GET['username'];
if(preg_match('/^[a-zA-Z]+$/', $username)) {
   echo(json_encode(array('Response'=>1)));
} else {
   echo(json_encode(array('Response'=>0)));
}

 

then it would be easy picking up the response using a library like jQuery, which has the $.getJSON function.

 

<script type='text/javascript'>
   $(document).ready(function() {
      $('input[name=username]').bind('keyup', function() {
         $.getJSON('validation_file.php', {username: $(this).val()}, function(data) {
            var response = parseInt(data[0].Response);
            if(response === 1) {
                // valid
            } else {
                // not valid
            }
         });
      });
   });
</script>
<input type='text' name='username'>

 

first you attach the keyup event to your field, which means the following function fires whenever the user releases a keyboard key, with the field in focus. It then checks the validation file (which contains the php part) and sends the username along in a $_GET variable. The php script then validates it using reg ex an returns an response array encoded as json. Please note i have not tested this code and it is highly likely to have flaws in it :)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.