HTML, XHTML and CSS All-In-One for Dummies - Andy Harris [177]
♦ Output the results. You can now process the results as you would with data from any other resource.
Working with Regular Expressions
Having the right kinds of form elements can be helpful, but things can still go wrong. Sometimes, you have to let the user type things, and that information must be in a particular format. As an example, take a look at Figure 6-5.
Figure 6-5: This page is a mess. No username plus an invalid e-mail and phone number.
A mechanism that checks whether input from a form is in the correct format would be great. This program implements such a feature, checking whether there is content in every field and ensuring the e-mail address and phone number are formatted correctly. You can create this kind of testing feature with string functions, but it can be really messy. Imagine how many if statements and string methods it would take to enforce the following rules on this page:
♦ An entry must appear in each field. This one is reasonably easy — just check for non-null values.
♦ The e-mail must be in a valid format. That is, it must consist of a few characters, an “at” sign (@), a few more characters, a period, and a domain name of two to four characters. That format would be a real pain to check for.
♦ The phone number must also be in a valid format. Phone numbers can appear in multiple formats, but assume that you require an area code in parentheses, followed by an optional space, followed by three digits, a dash, and four digits. All digits must be numeric.
Although you can enforce these rules, it would be extremely difficult to do so using ordinary string manipulation tools.
JavaScript strings have a match method, which helps find a substring inside a larger string. This tool is good, but we’re not simply looking for specific text, but patterns of text. For example, we want to know whether something’s an e-mail address (text, an @, more text, a period, and two to four more characters).
Imagine how difficult that code would be to write; then take a look at the code for the validate.html page:
-->