VirtualMV/JavaScript/Validation/Regular Expressions

Overview
Regular Expressions are a good way of validating text fields. Basically, you create a string of characters that represents a validation and test it against a string. This approach compacts a lot of potentially confusing validation code down into a few lines.

Example
In order to use a Regular Expression in JavaScript, you need to create a regex literal variable. So something like:

The above says "do a case-insensitive check for alphabetical characters and spaces only".

/ - Start of a JavaScript regular expression

^ - Match the first character with the following

[a-z - Match the letters a through to z

\s] - Match spaces

+ - Use the previous rule for every character in the string

$ - Match the last character

/i - End of a JavaScript regular expression, and also sets the mode to case-insensitive

(Andersson, 2008) gives an explanation of other patterns)

To test it against a string, we can use the "test" method that becomes available every time we create a variable containing a regular expression literal.

The above is just for a match case, search and replace can also be done using regexs, as well as splitting strings up into arrays etc.

Alternatively you can create a string and then create a new regular expression object, for example:

Example jsRegExp_01.htm

There are heaps of pre-created regular expressions available here:
 * RegexAdvice.com (2009)

RegExp Tester
If you want to explore and experiment with Regular expressions you can do this in real time at
 * http://iblogbox.com/devtools/regexp/

Resources

 * An Introduction to Regular Expressions (Chodnicki, 2011)
 * Dates and Times (RegExLibrary, 2011)


 * Contributors
 * ErinD Apr 2009