making sure a form entry contains only text and numbers
Moderator: General Moderators
making sure a form entry contains only text and numbers
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?
Check into regex and check ctype_alnum
- ReverendDexter
- Forum Contributor
- Posts: 193
- Joined: Tue May 29, 2007 1:26 pm
- Location: Chico, CA
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.ReverendDexter wrote:For the length issue, you can use the maxlength="x" property of the textbox.
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 allowedperfect!
this code works great:
(error is a funciton defined earlier in the whole thing)
how can I make a minimum number of characters?
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.');
}how can I make a minimum number of characters?
- RobertGonzalez
- Site Administrator
- Posts: 14293
- Joined: Tue Sep 09, 2003 6:04 pm
- Location: Fremont, CA, USA
Code: Select all
// min len 5, max len 25
$is_ok = (preg_match('#^[a-z\d]{5,25}$#i', $string)) ? true : false;