validating username

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
User avatar
jimthunderbird
Forum Contributor
Posts: 147
Joined: Tue Jul 04, 2006 3:59 am
Location: San Francisco, CA

validating username

Post by jimthunderbird »

Hi All,
I'm trying to validate a name containing only a-z, A-Z and hyphen, I found the following function works but looks illogical to me. Could you help me out?
Thanks.


Code: Select all

function nameValid($name){
      $name = trim($name);
      
      if(strlen($name)>0){
        if(!ereg('[^a-zA-Z-]{1,}', $name)){ // I am surprised at this line but looks like it works! Please help me out!
          return true;
        }
        else{
          return false;
        }
      }
      else{
        return false;
      }
    }
User avatar
Maugrim_The_Reaper
DevNet Master
Posts: 2704
Joined: Tue Nov 02, 2004 5:43 am
Location: Ireland

Post by Maugrim_The_Reaper »

It's a double negative - checking for a false return, from an opposing regex pattern match. The regex will match characters not matching the character range (i.e. if the string contains anything that is not alphabetic or a hyphen). If the regex fails to find a match, then the username is valid (hence the !ereg() check).

Using preg_match() might be a bit faster by the way, you just need to enclose the regex with a delimiter using the PCRE preg_*() functions like:

Code: Select all

%[^a-zA-Z-]{1,}%
% can be any character really though // or %% tend to be the most used - % in some cases since a forward slash can have special meaning in some regex strings.

An alternative would use preg_match() to completely match the string - I think that's a better method since it lets you also define a minimum and maximum length.
Post Reply