I have this PHP preg_match code that's suppose to only allow a-z (Capital and lowercase) 0-9 and underscores
But when I try signing up with the username "Rizon" it says: Only valid characters are allowed.
Here's the code:
if (!preg_match("[a-zA-Z0-9]_",$_POST['username'])) {
$_SESSION['error']['username'] = "Only valid characters are allowed.";
}
How can I fix the preg_match so it will allow usernames such as "Rizon" and usernames with uppercase and/or lowercase letters and/or numbers and/or underscores?
This should do the trick (you need to also check that username only contains your pattern)
if (!preg_match("/^[a-zA-Z0-9_]+$/",$_POST['username']))
Without adding ^
(start match) and $
(end match) your regular expression will only validate if a pattern is included.
try this
!preg_match("/[a-zA-Z0-9_]+/",$_POST['username']);
or
!preg_match("/[a-z0-9_]+/i",$_POST['username']);
Firstly you're missing delimiters for your regular expression. You could use /
or #
or any other of the available ones.
Next by the way you've declared the pattern to match again, it would translate to "match a single alphanumeric symbol followed by underscore".
So as already suggested use
[a-zA-Z0-9_]+
as a regex instead and use pattern delimiters
preg_match('/[a-zA-Z0-9_]+/',$_POST['username'])
You could also use the modifier i
for case insensitive
preg_match('/[a-z0-9_]+/i',$_POST['username'])
I think this would be the easiest regex.
if (!preg_match("~^\w+$~",$_POST['username'])) {
$_SESSION['error']['username'] = "Only valid characters are allowed.";
}
Demo: https://regex101.com/r/rG3sJ3/1
\w
is any character a-z, A-Z, 0-9, and an underscore. +
is one or more characters.
^
is the start of the string, $
is the end. Check the regex101 link for testing and more detailed description.
Links:
https://docs.oracle.com/javase/tutorial/essential/regex/pre_char_classes.html
https://docs.oracle.com/javase/tutorial/essential/regex/quant.html
https://docs.oracle.com/javase/tutorial/essential/regex/bounds.html
Come to think of it you probably want to do:
if (preg_match("/\W/",$_POST['username'])) { // check for non-word chars
$_SESSION['error']['username'] = "Only valid characters are allowed.";
}
And a separate validation for length:
if (!preg_match("/^.{6,8}$/",$_POST['username'])) { // check for length
$_SESSION['error']['username'] = "6 to 8 letters please";
}