Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression for validating a username?

Tags:

regex

php

I'm still kinda new to using Regular Expressions, so here's my plight. I have some rules for acceptable usernames and I'm trying to make an expression for them.

Here they are:

  • 1-15 Characters
  • a-z, A-Z, 0-9, and spaces are acceptable
  • Must begin with a-z or A-Z
  • Cannot end in a space
  • Cannot contain two spaces in a row

This is as far as I've gotten with it.

/^[a-zA-Z]{1}([a-zA-Z0-9]|\s(?!\s)){0,14}[^\s]$/

It works, for the most part, but doesn't match a single character such as "a".

Can anyone help me out here? I'm using PCRE in PHP if that makes any difference.

like image 206
dan Avatar asked Sep 29 '10 12:09

dan


1 Answers

Try this:

/^(?=.{1,15}$)[a-zA-Z][a-zA-Z0-9]*(?: [a-zA-Z0-9]+)*$/

The look-ahead assertion (?=.{1,15}$) checks the length and the rest checks the structure:

  • [a-zA-Z] ensures that the first character is an alphabetic character;
  • [a-zA-Z0-9]* allows any number of following alphanumeric characters;
  • (?: [a-zA-Z0-9]+)* allows any number of sequences of a single space (not \s that allows any whitespace character) that must be followed by at least one alphanumeric character (see PCRE subpatterns for the syntax of (?:…)).

You could also remove the look-ahead assertion and check the length with strlen.

like image 50
Gumbo Avatar answered Oct 05 '22 13:10

Gumbo