Home N-13 News Forums Help Search
RegisterForgot password?
How to add image to post necklacesdiscou
Known bugs - 4.0.3 necklacesdiscou

Latest N-13 News 4.0.3

What is N-13 News?
Where can I get help?
Known bugs

Forums Tutorials Username validation
Chris
Posted on 14 Jun 2006, 08:32:31

Access: Admin
Total Posts: 1395
Joined: 2006-05-19

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.

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.";
 }
>
#1
Last edited by Chris at 2006-06-29 19:06:59 Reason:
Network-13.com © 2013