1

I need a regex that allow user to insert a password in a field. But the only allowed regex are [A-Za-z0-9] ok, but also "space", ".", "_", "-". How can is possible allow the special chars I listed, but NOT TO FORCE user to use that? On the other hand, disallow all the other special chars.

Is it possible?

With this code I check the quality of the password, but not sufficient for my goal cause I cannot manage the special chars:

            else if ($check_strength && (!preg_match("/[0-9]/", $newpwd) || !preg_match("/[^A-Za-z0-9]/", $newpwd))) {
            $rcmail->output->command('display_message', $this->gettext('passwordweak'), 'error');
        }

I've solved my problem with this one:

"/^[A-Za-z0-9\.\-\_]+$/"
3
  • You already know how the character class works? Just add the additional characters into there. Commented Apr 11, 2012 at 15:28
  • 1
    Also: there is no reason for you to restrain passwords. You can limit allowable usernames, but passwords ain't your business. It doesn't enhance usability, and most certainly not security. Commented Apr 11, 2012 at 15:29
  • That's the simple solution for me: "/^[A-Za-z0-9\.\-_]+$/" Commented Apr 11, 2012 at 16:39

3 Answers 3

1

If I understand correctly, this regex would do that:

/^[a-zA-Z \._\-]+$/
Sign up to request clarification or add additional context in comments.

Comments

0
echo preg_match("/^[A-Za-z0-9 ._-]+$/", '-a. s_d'); // 1

or more abbreviated:

echo preg_match("/^[\w .-]+$/", '-a. s_d'); // 1

2 Comments

Ok this worked for me. But can you explain me about the space? Where is it in the abbreviated version?
after the \w and before the .
0

You shouldn't "check" the user's password with a regex. I advise you to check the strength with metrics and ensure that it's considered as "strong enough" (for example of metrics look at this site).

This way, the user can have any character in his password. You shouldn't really care about what characters the user choose in his password, and you will hash that anyway, so it doesn't affect you.


That said here is your regex:

[\w .-]+

Comments

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.