Hi,

I have the following regex pattern. I don't think there is anything wrong with it. It seems to work when i test but if someone sees anything wrong with it please feel free to tell me.

I don't know Regex but managed to put a username validator together as my previous one was limited.

The problem i have is i want the username so it has to contain letters at least but cannot be all numbers, so if a user tries to use all numbers they have to add a letter to it for it to be valid, but it is fine if it is just all letters.

Because at the moment i am able to create a username like: 123456

Obviously this is not very good, hence why i want it so they have to add a letter if using all numbers but if using all letters then no number is required and optional.

Currently it works like this. A user can have a username between 3-15 characters and can contain _-*. characters and must begin with a letter or number.

if ( !preg_match('/^[a-zA-Z0-9][a-zA-Z0-9_\-\*\.]{3,15}$/', $_POST['username'])) {
     $err++;
	 echo "<span class=\"error\"><p>My Error Message Here.</p></span>";
}

I hope i have not confused you.

Thanks for any help.

Genieuk

Recommended Answers

All 4 Replies

if ( !preg_match('/^\w[\w_\-\*\.]{2,14}$/', $_POST['username']))

\w matches letters and digits
{2,14} because you did not count the first \w An iterator applies only to the previous element, if no specific grouping applies.

I was working on this, I think it should work (at least in regexbuddy it does)

^(?!^(\d+)$)[a-zA-Z-0-9][\w_\-\*\.]{2,14}$

which uses a negative lookahead to match a digit only username.
For some reason starting with \w here doesn't work.

Thanks Pritaeas,

Not got a clue, i find it somewhat confusing.

Maybe someone who knows more about regex could assist on this?

Thanks.
Genieuk

if ( !preg_match('/^(?!^(\d+)$)[a-zA-Z-0-9][\w_\-\*\.]{2,14}$/', $_POST['username']) )
{
  // invalid
}

As far as I can see, this works.

As far as I can see, I don't know why genieuk can find it confusing,
it is advanced regex and he wants to ask someone who knows MORE about regex? ehr.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.