View Full Version : How do I test for alphanumeric expressions in input field

09-12-2011, 07:34 AM
I searched the forum for an answer to this question, but found nothing that was able to answer my question. I have a form and I need to validate a field against three rules:

1) The field need to be between 6 and 12 characters
2) It can only have letters, numbers, and the underscore
3) It cannot contain a space or other special characters

I want the validate to happen in real-time. I have the first rule working great. Here is the code for that:

var username = document.getElementById('registerUsername');
if((username.value.length < 6) || (username.value.length > 12))
How would I be able to incorporate checking for rules 2 and 3?

09-12-2011, 08:26 AM
You can do all this with one single regex

var myRegex = /^[a-zA-Z0-9_]{6,12}$/;
if(myRegex.test(document.getElementById('registerUsername'))) {
// correct format here
} else {
// format is not correct

09-12-2011, 01:44 PM
Also notice how this

var myRegex = /^[a-zA-Z0-9_]{6,12}$/;

is the exact same thing as this:

var myRegex = /^\w{6,12}$/;

which makes the whole thing even easier.

09-12-2011, 02:13 PM
Woah ... I never noticed the underscore was already part of \w ... thanks