2
if(preg_match("%(?=.{8})[A-Za-z0-9]([.-]{0,1})%", stripslashes(trim($_POST['username']))))

I want the username to be at least 8 characters A-Za-z0-9 with only 1 . or 1 - . How do I implement this? My code is allowing a username of ".............." as valid. <- Don't want that.

BTW: the "." or "-" is meant to be optional.

2 Answers 2

4

Sometimes, regular expressions just aren't the right tool for the job.

$username = stripslashes(trim($_POST['username']));

if(preg_match('/^[a-zA-Z0-9.-]{8,}$/', $username)
&& substr_count($username, '-') <= 1
&& substr_count($username, '.') <= 1) {
    # It's valid.
}
Sign up to request clarification or add additional context in comments.

Comments

2

A quick patch would be to count those characters after the first check.

i.e.,

 if (strlen(preg_replace("#[^.-]#", '', $username)) > 2)
     // Not valid.

This is not the check you asked for, this counts .'s and -'s together, so two dots or two dashes would be considered valid. But it's quick and easily extended to more characters.

8 Comments

Ty for your response however minitech's solution worked for me.
Good! But I was going to suggest a change -- maybe "/[A-Z][A-Za-z0-9.-]{7,}/" would do better, because I don't think you would like usernames like ".htaccess" :-).
I guess I can make that change. Just curious though how would a username such as ".htaccess" be malicious? Meaning would it be a threat to my security in anyway by allowing a person to have this username? Ty for your input btw
btw the correct code to prevent a username like .htaccess and still adhere to my other requirements would be: '/^[A-Za-z0-9]+[A-Za-z0-9.-]{8,}$/'
No, no, no security problem whatsoever. Actually I'd love an username like that, it would be cool :-)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.