Tuesday 14 August 2018

Simple Username Creation Validation with PHP

When I create login areas (mostly intranets) for small websites, I'm always asked by the customer to keep usernames to letters and numbers. That means no email addresses as usernames and special characters like "_", "-", and ".". This, in my customer's mind, keeps the login easy for their users and limits the number of support calls they will receive. While I don't recommend disallowing common username characters like the ones cited above, I do understand their need for simplicity. Here's how, using PHP, I validate that a username is only letters and numbers.


The PHP
function validate_username($input,$pattern = '[^A-Za-z0-9]')
{
return !ereg($pattern,$input);
}
It's as easy as that. I don't go as far as using this for passwords, but you could if you wanted to. I'll also mention that if I want to allow non-alphanumeric characters, I just need to change the function's pattern. Easy enough!

0 comments:

Post a Comment