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.
The above says "do a case-insensitive check for alphabetical characters and spaces only".
^ - 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
(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:
There are heaps of pre-created regular expressions available here:
- RegexAdvice.com (2009)
|Regular expression||What it does|
|/^[A-Z\s]+$/;||Check for Uppercase A-Z plus space|
|/^[0-9]+$/;||Check for integer e.g. 123,|
|/^(19|20)\d\d[- /.](0[1-9]|1)[- /.](0[1-9]|[0-9]|3)$/;||matches a date in yyyy-mm-dd format from between 1900-01-01 and 2099-12-31, with a choice of four separators (-,/,space, and .) |
If you want to explore and experiment with Regular expressions you can do this in real time at
- An Introduction to Regular Expressions (Chodnicki, 2011) 
- Dates and Times (RegExLibrary, 2011)
- ErinD Apr 2009
- RegexAdvice.com (2009) Regular Expression Library. Retrieved May 13, 2009 from http://regexlib.com/
- Regular Expression Matching a Valid Date. Retrieved May 26, 2011 from http://www.regular-expressions.info/dates.html
- (Chodnicki, S.(2011). An Introduction to Regular Expressions. Retrieved from http://type-exit.org/adventures-with-open-source-bi/2011/05/an-introduction-to-regular-expressions/
- RegExLibrary (2011) Dates and Times. Retrieved May 26, 2011 from http://www.regxlib.com/DisplayPatterns.aspx?cattabindex=4&categoryId=5