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 :)

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.