Simple JavaScript Validation using Regex
Sometimes it is important to validate a users input, such as entering a number, decimal value or an email address. Validation of the input can occur in two locations, the Client and Server realm. The Server realm allows us to validate user input one the user has pressed the submit button. We receive the users input and we can easily validate their input for the correct format. You should always validate a users input on the server side.
To make the process quicker you should also take advantage of the client realm as well. This will allow you to quickly pick up mistakes and allow the user the opportunity to fix the mistakes before submitting the form to the server for validation.
A great way of checking the simple input it to use JavaScript Regular Expressions.
Regular expressions can be both used on the Client and Server side to ensure that an inputted text contains the correct format. This may be checking that the input is only numbers, or is a number with a decimal value etc.
Regular expressions are very easy to implement and are very reusable.
I simple way of invoking a validation check is to use the form elements event handlers (onchange, onblur etc).
< input id="myfield" name="myfield" onchange="javascript:validate('myfield',currencyRegex,'Please ensure the value you have entered is a currency format (x.xx)');" />
My generic validate JavaScript file – validate.js contains:
< !—
// REGEX
var currencyRegex = /^\d+\.\d{2}$/;
var numberRegex = /^\d+$/;// Validate Function
function validate(fieldId, regex, message) {
field = MM_findObj(fieldId).value; // You can use document.getElementById(fieldId).value; but I prefer using Macromedia’s MM_findObj javascript function
if(!field.match(regex)) {
alert(message);
}
MM_findObj(fieldId).focus();
}
–>
You can then find and collect various regex expressions commiting them to your standard validate.js file, and use them often to help ensure feedback of simple string matching/formats is quick and does not require the user to hit submit for server side response.
Various JavaScript REGEX’s can be found through google very easily, and the syntax is very easy to learn, and very powerful.






Two sites that are useful for learning about Regex:
Jon Oxer Cheat Sheet
http://jon.oxer.com.au/regex-cheat-sheet.php
Perl Regular Expression
http://www.itlab.musc.edu/docs/perl_regexp/
Comment by Cameron Manderson — March 14, 2006 @ 4:01 pm