Form Validation with JavaScript Regular Expressions (Part 1)
(Page 1 of 5 )
Forms are one of the most useful ways to collect information online from customers and potential customers who visit your website. But that information is just a waste of electrons if it is not correct. How can you validate it? This article explains some of the building blocks you can use in JavaScript to at least ascertain that information entered into a form is in the expected format.
The method used to collect information from customers and visitors to your site is an extremely versatile and adaptable tool. Whether you want to allow people to sign up for your monthly newsletter, collect customer feedback or maintain a customer information database, you will probably collect the information directly from your customers using a form, among other things. Basic forms are extremely easy to code, and while they won't actually process any of the information entered into them, without them you would not have a mechanism to collect the information in the first place.
But there is no use collecting information that is clearly incorrect. Unless you're a corporate site administrator, there will probably be a limit to the amount of information you can hold in a database, and therefore it makes no sense to fill the database with incorrect information. Something is needed to ensure that users entering data into your forms are entering data that you can use and that meets your expectations of the data.
Regular Expressions can be used as a way of matching patterns in strings. By patterns, I mean specific occurrences of letters, numbers or punctuation marks. This is an extremely effective way of checking that the information visitors to your site have entered into your forms is correct. When I say correct I mean generally in the correct format; if a user spells their name incorrectly when entering their email address, there's not a lot you can do. But if they enter it and fail for some reason to include the @ character, for example, this at least can be detected. There is a home for regular expressions in any form, and almost any field that requires character input can be checked.
You define a regular expression that matches correctly entered data and then passes the form to the relevant CGI app, or you can define regular expressions that match incorrectly entered data and output an error message if this data is entered. A combination of these two approaches will ensure that you are given data in a format that you are able to work with.
Next: Regular expressions in JavaScript >>
More JavaScript Articles
More By Dan Wellman