0

I'm trying to make functions for validating usernames, emails, and passwords and my regex isn't working. My regex for usernames is ^[a-zA-Z0-9 _-]$ and when I put anything through that should work it always returns false.

As I understand it, the ^ and $ at the beginning and the end means that it makes sure the entire string matches this regular expression, the a-z and A-Z allows all letters, 0-9 allows all numbers, and the last three characters (the space, underscore, and dash) allow the respective characters.

Why is my regular expression not evaluating properly?

mickmackusa
  • 37,596
  • 11
  • 75
  • 105
liaquore
  • 391
  • 5
  • 19

2 Answers2

2

You need a quantifier, + or *. As it was written that only allows 1 of the characters in the character class.

Your a-zA-Z0-9_ also can be replaced with \w. Try:

^[\w -]+$

+ requires 1 or more matches. * requires 0 or more matches so if an empty string is valid use *.

Additionally you could use \h in place of the space character if tabs are allowed. That is the metacharacter for a horizontal space. I find it easier to read than the literal space.

Per comment, Update:

Since it looks like you want the string to be between a certain number of characters we can get more specific with the regex. A range can be created with {x,y} which will replace the quantifier.

^[\w -]{3,30}$

Additionally in PHP you must provide delimiters at the start and end of the regex.

preg_match("/^[\w -]{3,30}$/", $username);

Additionally, you should enable error reporting so you get these useful errors in the future. See https://stackoverflow.com/a/21429652/3783243

user3783243
  • 5,098
  • 5
  • 16
  • 37
  • 1
    That still doesn't work. This is my code: ``` function valid_username(string $username) { $username_length = strlen($username); return ($username_length >= 3 && $username_length <= 30 && preg_match("^[\w -]+$", $username)); } ``` – liaquore May 31 '19 at 12:17
  • string(4) "Test" – liaquore May 31 '19 at 12:19
2

You're not specifying the character count. Lets try this instead:

^[A-z0-9]*$

Where [A-z0-9] states that you can use any alphanumeric characters and that it is case sensitive.

The * specifies how many characters, and in this case is unlimited. If you wanted to max out your username length to 10 characters, then you could change it to:

^[A-z0-9]{10}$

Whereby the {10} is specifying a maximum of 10 characters.

UPDATE

To also allow the use of underscores, hyphens and blank spaces (anywhere in the string) - use the below:

^[A-z0-9 _-]{10}$
Mark
  • 676
  • 6
  • 19