Jump to content

Match allowed names


bearruler

Recommended Posts

I have a little experience with Regular expressions, but this one is just pissing me off
Im sure its so simple, but everything I have tried/found doesnt work

All I need is a simple pattern to validate names on my website. Names can have letters (case doesnt matter, must start in a letter), numbers, underscores, and dashes

Allowed names:
bearruler
bearruler129
bear_ruler
bear-ruler
be-ar_ru13r

Illegal names:
_bearruler
bear ruler
129bearruler
bear@ruler
bearru|er
{bearruler}

You get the point...

Anyway, the php should be
[code]
$name="The Name They are attempting to use";
$pattern='thepattern';
if (preg_match($pattern, $name)) echo "ok";
//etc...
[/code]

Does anyone know a pattern that will fit this?

Thanks,


Bear
Link to comment
Share on other sites

try this pattern:

^(?=.*?[\d])?(?=.*?[a-zA-Z])(?=.*?[\-\_])?[a-zA-Z][\-\w]{8,25}$/s

note the {8,25} this requires that usernames are at least 8 characters but no more than 25 characters long. Why? I have found that very long usernames cause trouble in the long run. If you want more combinations allow dots(.) or other symbol in your usernames.

To remove this restriction simply replace {8,25} with * or +

Link to comment
Share on other sites

[code]
<?php

### Set up test cases.
$tests = array(
### Should pass.
'bearruler',
'bearruler129',
'bear_ruler',
'bear-ruler',
'be-ar_ru13r',
### Should fail.
'_bearruler',
'bear ruler',
'129bearruler',
'bear@ruler',
'bearru|er',
'{bearruler}',
);

### Run tests.
foreach ($tests as $test) {
echo "$test --";
echo preg_match('/^[a-z][-\w]+$/i', $test) ? 'Pass' : 'Fail';
echo '<br />';
}

?>

[/code]
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.