A Feedback Form
In this section we'll show you how to create a feeback form that checks if the user's e-mail address' syntax is valid. We'll first provide the script, and then explain it in depth. The final result looks like this:
Enter a string in the "e-mail" field, and submit the form. If your string is a valid e-mail address, the script accepts it (and would submit the form, but this is just a demo). If the string is not a valid e-mail address, a message is displayed and the field is highlighted for easy correction. Note that this specific form does not send me an e-mail, because it's just a demo! Here's the code for this form and its corresponding script:
If you're using a browser that doesn't support regular expressions, you'll get an immediate error. In the following section we'll show you how to solve this problem.
Take a look at the
<FORM> tag, which defines the form's main attributes. You should change the e-mail address to your own, so the user sends you an e-mail when he or she submits the form. The
onSubmit event handler provides the ability to cancel the submission if it returns
false. The statement
return valid(this) simply returns the value that is returned by the
valid() function. If the function returns
false (it does that when the user's e-mail address has an invalid syntax) the form's submission is cancelled. Otherwise, the submission proceeds. The term
this.email, for example, would refer to the field named "
Now let's see how the function works, and what it does. First, it assigns the variable
field an object that reflects the e-mail address field. The value of this field is then assigned to the variable
str. The function then defines two regular expressions:
reg2. The first one matches common invalid e-mail addresses, whereas the second one matches the general e-mail address syntax. By combining these two expressions (we negate the first one, of course) we achieve a relatively reliable e-mail verification mechanism.
The function utilizes a simple
if statement to check if the e-mail address' syntax is valid. If so, it displays a message and returns
true, so you (
firstname.lastname@example.org) receive the user's e-mail. Otherwise, an alert is displayed and the e-mail address field is highlighted, so the user can easily edit the address. The function then returns
false, cancelling the submission.
The first regular expression is very obvious, but the second one is a bit more difficult. It matches the basic syntax of an e-mail address, according to the following rules (in order of appearance):
- One or more characters before the "
- An optional "
email@example.comis a valid e-mail
- A sequence of letters, numbers, and periods, which are all valid domain or IP address characters
- A period followed by a 2-3 letter suffix
- An optional "
Created: October 23, 1997, 1997
Revised: December 4, 1997