JavaScript: validate forms with Regular Expressions (RegEx)

I know I've been posting a lot on forms and validation recently, however we should all agree on the fact that form validation is really a serious problem for programmers.

When a user submit data to our database, the first thing we should consider is to protect the destination. Our database is waiting for specific data and, for example, a text string must not be submitted to a smalldate field.
On the other hand, we should provide a complete and efficient way to help the user in filling in the form. Specifically in commercial situations, if we want the visitors to conclude painlessly a commercial transaction, we should make things the easiest possible way for him/her.

When we check what the user is submitting, we can be sure that the birth date or the credit card expiration date is truly a valid date - for the user protection and security and for the web site owner who needs to be sure that everything works smoothly.

In the following example, we are going to validate emails, however, by changing the regular expression, we can check almost anything.
In the following example we use RegEx in a short JavaScript function.


What we need is just submit the email address to the function, and we will receive a true or false response.
Let's see the function:
function validate(email){
   var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
    if(filter.test(email)){
        return true;
    }
    else{
        return false;
    }
}
Just a few side notes on the above function:
1) the target browser must be JavaScript enabled (and that's obvious);
2) if you can use HTML5... well, use it with type="email" (see here);
3) the RegEx used is just a simple one. A RFC 2822 compliant expression is much more complicated.

If you want to explore more, see the Regular Expression site where you can find expressions for:
  • numeric ranges;
  • floating point numbers;
  • email addresses;
  • dates;
  • credit card numbers;
  • matching complete line;
  • deleting duplicate lines;
  • programming;
  • two near words.

Use the above code wisely and enjoy!