Page 1 of 1

Need username validation regex

Posted: Fri Feb 06, 2009 2:03 pm
by yacahuma
Hello


I need a regular expression to validate usernames


Also is there any good standard on valid usernames(ie, characters that shoould never be allowed)


Thank you

Re: Need username validation regex

Posted: Fri Feb 06, 2009 2:31 pm
by prometheuzz
yacahuma wrote:Hello


I need a regular expression to validate usernames
Try php's preg_match(...) function.
yacahuma wrote:Also is there any good standard on valid usernames(ie, characters that shoould never be allowed)

Thank you
Perhaps not "the" standard, but a reasonable set of rules are:
- only ASCII;
- no spaces (or tabs or white new line characters);
- only printable characters (not bell-char etc).

Re: Need username validation regex

Posted: Fri Feb 06, 2009 3:29 pm
by yacahuma
will this be good enough

Code: Select all

 
 function isValidUsername($string,$min,$max)
   {
        return preg_match("/^[a-zA-Z0-9_.-]{{$min},{$max}}$/", $string);
   }
 

Re: Need username validation regex

Posted: Fri Feb 06, 2009 3:46 pm
by prometheuzz
yacahuma wrote:will this be good enough

Code: Select all

 
 function isValidUsername($string,$min,$max)
   {
        return preg_match("/^[a-zA-Z0-9_.-]{{$min},{$max}}$/", $string);
   }
 
That looks like a reasonable set for usernames, yes.
Note the set "[a-zA-Z0-9_]" can be written as "\w" making your regex look like:

Code: Select all

"/^[\w.-]{{$min},{$max}}$/"
but some people find the longer version easier to read. Just so you know.

Good luck!

Re: Need username validation regex

Posted: Fri Feb 06, 2009 3:54 pm
by prometheuzz
yacahuma wrote:will this be good enough

Code: Select all

 
 function isValidUsername($string,$min,$max)
   {
        return preg_match("/^[a-zA-Z0-9_.-]{{$min},{$max}}$/", $string);
   }
 
Of course, that will also accept user-names like "-a_name...", "na-.-.-.-.me" or ".....another-name". You could enforce possible restrictions of:
- a user-name should start and end with a letter or digit;
- a user-name cannot have two successive '-', '.' or '_'

Your regex would then look like:

Code: Select all

"/^[a-zA-Z0-9]+([._-][a-zA-Z0-9]+)*$/"
And the length of the string could be handled by the built-in function 'strlen':

Code: Select all

$n = strlen($string);
return $n >= $min && $n <= $max && preg_match("/^[a-zA-Z0-9]+([._-][a-zA-Z0-9]+)*$/", $string);
Hope that helps.

Good luck!

Re: Need username validation regex

Posted: Sat Feb 07, 2009 3:07 am
by GeertDD
prometheuzz wrote:Note the set "[a-zA-Z0-9_]" can be written as "\w"
Watch out with \w, remember?

Re: Need username validation regex

Posted: Sat Feb 07, 2009 3:14 am
by prometheuzz
GeertDD wrote:
prometheuzz wrote:Note the set "[a-zA-Z0-9_]" can be written as "\w"
Watch out with \w, remember?
; )

While submitting my post, I just thought of your thread! (but must admit I was too lazy to look it up... :oops: )