JavaScript - Regular Expressions

A regular expression is a pattern that uses a special syntax to describe the content of a text field. It can be used either to validate that the string contains a valid value or alternatively it can be used to format a value entered so that it matches the specified format.
Regular expressions were introduced into Javascript in version 1.2 and so can be used to perform field validations in all modern browsers. While the actual syntax of regular expressions is quite complex compared to most other Javascript commands, once you have the code for a particular regular expression using that expression to perform validation on an input field is very easy.
Here are a couple of regular expressions :

emailRe = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*\.(\w{2}|(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum))$/

phoneRe = /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/

Note that the expressions are fairly long and that in order for them to work correctly they each need to be coded completely on one line (if you select the code in the above box and paste it into a text editor you should get the code set out correctly). These examples define valid formats for email addresses and phone numbers respectively.
The email address regular expression accepts email addresses in the format username @ domain name. There are a couple of other valid email address formats (eg. username @ [ip address]) but this regular expression only accepts the more common format.
The phone number regular expression accepts phone number in both local format (eg. 02 1234 5678 or 123 123 4567) or international format (eg. +61 (0) 2 1234 5678 or +1 123 123 4567). It also accepts an optional extention of up to five digits prefixed by x or ext (eg. 123 123 4567 x89).
Rather than performing a whole series of validations to validate that a given field contains an email address or phone number you can perform one test using the appropriate regular expression instead. For example, the following code could be used with the above regular expressions to validate two fields on your form.
if (!emailRe.test(myform.replyemail.value))
alert(myform.replyemail.value + ' is invalid');
if (!phoneRe.test(
alert( + ' is invalid');
Note that like any other validations that you perform against form fields using Javascript, you cannot validate that the entered value actually exists and is correct. All you can do is to check that it matches to an expected pattern. Any more substantial validation would require server side processing as Javascript does not have access to anything that allows it to perform that additional validation.

No comments:

Post a Comment