On my previous post, I discussed how to validate Twitter username in PHP using Regular Expression (regex). As my project required me to perform the validation on both the client and server side, I had to come up with a JavaScript solution to validate the Twitter username. So, I created a function within an external JavaScript file and included it with the html document to check the user inputs whenever I need it.
Now, this is how the validity testing method works.
<script>
var username = "twitterUser";
var expr = /^[A-Za-z0-9_]{1,15}$/;
alert(expr.test(username));
</script>
As you can see from the snippet, I am using .test() method to check against the string (username) provided by the user. The literal regular expression is exactly the same as I mentioned on my previous post. The test result will be alerted on this case but you can return the response to the script back and move on with handling the rest of the process accordingly.
One of the primary reason why I am using .test() method over .match() is because .test method provides a boolean (true/false) response. On the contrary .match method returns the full string back if it matches with the expression otherwise it would simply return null which is a bit inconvenient for me.
Trust me there are lots of different opinion over this issue but I decided to move on with .test method regardless. We already learned from jsPerf site's test result that .test method performs significantly faster over .match on almost all the web browser. So, there shouldn't be any question on this afterwards.
Comments