Login

Member statsTotal: 206Latest: CcardinGuests online: 8Members online: 0
EmailLogin here

Location
ForumPHP Tutorials • Username validation

Access: Admin
Total posts: 174

Status: Offline
Username validation Quote 

PHP Code:
<?php
function validate($string){
$s = strtolower($string);
  if(!
preg_match("/^(?i)[a-z0-9_]*$/", $string)){
          
#checks if the username contains any strange characters
          
return "dirty can only have letters a-z, numbers 0-9 and underscores _";
  }elseif(!
preg_match("/^(?![0-9_]).*$/", $string)){
          
#checks if the username entered begins with a number or underscore      
          
return "dirty can't begin with a number or underscore";
  }elseif(
preg_match("/__/", $string)){
          
#checks if the username has more than 1 consecutive underscores
          
return "dirty can't have consecutive underscores";
  }elseif(
substr($string,(strlen($string) - 1), strlen($string)) == "_"){
          
#checks if the username ends with an underscore      
          
return "dirty can't end with an underscore";
  }elseif(
strlen($string) < 3){
          
#checks if the username is less than 3 characters in length      
          
return "dirty must be at least 3 characters long";
  }elseif(
strlen($string) > 20){
          
#checks if the username is more than 20 characters in length      
          
return "dirty  must be less than 20 characters long";
  }else{
          
#if everything seems to be fine return "clean"
          
return "clean";
  }
}
?>


This is the same function I used to verify a user enters a valid username when registering an account.

When the function is called it checks the string entered by the user, if that string fails any of the checks the function returns "dirty ..." followed by a description, if it finds no problems with the username it'll return clean.

To use it simply enter the string into the function as follows.

PHP Code:
<?php
$str
= "Chris"; #test username

#if the validate function returns the word dirty then you know its found a fault in the username
if(ereg("dirty",validate($str))){
    
#replace the word 'dirty' with 'username' then print out the error
    
$error = str_replace("dirty","Username",validate($str));
    echo
$error;
}else{
    
#username has no problems
    
echo "Username is fine.";
}
>
03:32am 14th Jun 06
_______________
Chris - Network-13
Last edited by Chris at 02:06pm 29th Jun 06
Post a reply!