Jump to content

Archived

This topic is now archived and is closed to further replies.

bearruler

Match allowed names

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

Share this post


Link to post
Share on other sites
Have a read of [url=http://www.phpfreaks.com/forums/index.php/topic,99116.0.html]this topic[/url] maybe. As its basically the same as what you are doing.

Share this post


Link to post
Share on other sites
I tried everything in there, it returns 1 for things like bearruler, but also names like bea$$rruler


Bear

Share this post


Link to post
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 +

Share this post


Link to post
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]

Share this post


Link to post
Share on other sites

×

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.