Page 1 of 1
making sure a form entry contains only text and numbers
Posted: Wed Jun 27, 2007 10:38 am
by suthie
How can I make it so that when a user is creating a username, php checks to make sure it is only letters and numbers and also limit the amount of characters in the entry?
Posted: Wed Jun 27, 2007 10:58 am
by Z3RO21
Check into regex and check
ctype_alnum
Posted: Wed Jun 27, 2007 12:12 pm
by ReverendDexter
For the length issue, you can use the maxlength="x" property of the textbox.
Posted: Wed Jun 27, 2007 12:26 pm
by Z3RO21
ReverendDexter wrote:For the length issue, you can use the maxlength="x" property of the textbox.
But you will want to check with strlen as well, regex can also be setup to require a certain min and even a max number of characters. Reason for this is the HTML can be altered and the maxlength property can be changed.
Here is an example of regex:
Code: Select all
$regex1 = new regex('/^[a-zA-Z0-9]$/'); //Charecters a-z, A-Z, and 0-9 no limits
$regex1->test('test123TEST'); //true
$regex1->test('test 123'); //false has a space
$regex1->test('test!@#'); //false has non-alphanumeric characters
$regex2 = new regex('/^[a-zA-Z0-9]{3,}$/'); //Characters a-z, A-Z, and 0-9 must be at least 3 characters
$regex2->test('abc'); //true
$regex2->test('a'); //false has too few characters
$regex3 = new regex('/^[a-zA-Z0-9]{3,10}$/'); //Characters a-z, A-Z, and 0-9 must be between 3 and 10 characters
$regex3->test('dsfsd'); //true
$regex3->test('d'); //false again has too few characters
$regex3->test('dsfsdhfghghgfhfghghgf'); //false has more characters than allowed
*note I am using a regex class of mine. the function test(string) is a wrapper for preg_match. And you can use character classes with regex (ex. /w) to represent groups of characters (ex. /w = [a-zA-Z0-9]).
Posted: Wed Jun 27, 2007 1:43 pm
by suthie
perfect!
this code works great:
Code: Select all
if (!ctype_alnum($username)){
error('Usernames must consists of only letters and numbers..\\n'.
'Please create a username that contains only letters and numbers.');
}
(error is a funciton defined earlier in the whole thing)
how can I make a minimum number of characters?
Posted: Wed Jun 27, 2007 1:47 pm
by RobertGonzalez
Posted: Wed Jun 27, 2007 2:07 pm
by suthie
perfect! thanks!
Posted: Wed Jun 27, 2007 2:13 pm
by Benjamin
Code: Select all
// min len 5, max len 25
$is_ok = (preg_match('#^[a-z\d]{5,25}$#i', $string)) ? true : false;