Recently I was working on a project where I had to come up with a solution to validate twitter username before I allow users to insert the data into my database. Now, as far as the rules for choosing your twitter username is concern, twitter allows only alpha numeric characters (letters & numbers) with the exceptions of underscore (_). It is important to note that both the lowercase and uppercase letters are allowed while the username can not be more than 15 characters long.
This is fairly simple and easy to understand. Here how it should work in PHP.
<?php
$username = 'myUsername1_';
if (preg_match('/^[a-zA-Z0-9_]{1,15}$/', $username)) {
echo 'valid';
} else {
echo 'invalid';
}
?>
The snippet above should echo out "valid" on your php page. Feel free to play around use it as you wish. If you pay attention to our Regular Expression (regex), you can see I wrote "{1,15}", which means there (username) should be minimum of 1 and maximum of 15 characters. I am not sure about the minimum characters that twitter allows so I simply used 1 but dig your way to figure that out.
As a side note, please understand that if you are performing such operation on your system (which I am) frequently, you are better off writing your own methods to perform such operation for the sake of simplicity and convenience. I hope you understood what I meant.
It is quite important to understand that such validation can also be perform from client's side as well using JavaScript. However, on a personal level I follow both the client and server side validation before I finally sanitize the data and only then insert them into the database. I expect to discuss the client slide validation on my next post using JavaScript. Thank you.
Comments