Form Validation with JavaScript Regular Expressions (Part 2)
Form validation is an issue many websites must deal with. In this second article in a two-part series, you will use the JavaScript regular expressions you learned in the first article to put together a script that will validate a range of form inputs.
Form Validation with JavaScript Regular Expressions (Part 2) - User-friendly enhancement (Page 2 of 4 )
I haven’t included it in this example, but another user-friendly feature that would enhance this form would be a function using the focus method, which highlights all of the text in a field if that field is selected. This means that the user can easily retype any invalid answers. This example has been tested and found to work on MSIE, Netscape Navigator 7 and FireFox, so you can be sure that a wide base of visitors will find this form fully functional.
We can then build the following script that is inserted into the head of the document and called on submission of the form. If this page were to be used on the Internet, it would be a good idea to separate the script from the main document, and allow it to reside in its own file in a protected folder within the site’s directory structure (probably the scripts folder). This would be safer, as the file would not be directly viewable, and would therefore not expose the logic behind your validation scheme. Forms have traditionally been popular points of entry for hackers.
First, you need to get all of your field inputs into variables that the script can work with. These will go at the very beginning of the validate() function: