Validating Forms with Regular Expressions
By Al Williams
Many developers use client-side JavaScript to test and validate data that customers enter into forms. Why send data to the server if you can determine its validity at the browser? Unfortunately, most of the JavaScript validation schemes I've seen have been very inflexible. For instance, many scripts validate data when the customer submits the form, but only a few provide instant feedback while the user enters data. And many scripts are customized to a specific form so that each change to the form requires more work on the developer's part, adding and deleting code from a single, monolithic validation function.
One way to get around some of these limitations is to use regular expressions. If you're familiar with Unix or Perl, or formal mathematics, you've probably used regular expressions to specify and look for patterns. Pattern matching is more efficient and powerful than looking for specific instances of hard-coded data. In the case of online forms, you can write a generic script that uses regular expressions for a quick test and validation of the data supplied by your customers. You can also extend that script with just a little more work to format data automatically as the customer enters itfor example, adding hyphens in the right places to phone and credit-card numbers.
About Regular Expressions
With regular expressions you can define how your data should look. The basic idea is that you can use these expressions in your code to search a bit of text for a particular pattern.