Verify Email Address - Examples |
How to validate an email address
It is often required that two fields in a form are compared, for example to ensure an email address has been entered accurately.
The forms below each show two fields, and use Javascript fired by the onchange event to ensure the contents of the fields are identical.
These examples also check that the email address is in a valid format (not that the address is genuine), but - a big but - the validity check may exclude some valid addresses where accented characters are used.
The forms onsubmit event should be used to validate the contents of these fields, as well as any other fields in the form. Do NOT use the onclick event on the submit button - it is possible to submit a form by pressing the Enter key without touching the submit button.
This form submits to itself, so after submitting check the querystring in the URL to see the values for email and check email fields (email1 and email2 respectively). The querystring is repeated here (with each parameter on its own line) for convenience:
fl=2009011400
The javascript used is the same as in the main article.
The form HTML is:
<form id="contact" action="email-check.htm" method="get" name="contact" onsubmit="return chkvals(2)"> <p><label for="email1" style="width:150px;text-align:right;float:left;padding:.4em 1em 0 0;">Email</label><input class="inp" name="email1" id="email1" onchange="compFields(2)" type="text" /></p> <p><label for="email2" style="width:150px;text-align:right;float:left;padding:.4em 1em 0 0;">Retype Email</label><input class="inp" name="email2" id="email2" onchange="compFields(2)" type="text" /></p> <p style="padding-left:160px;"><input class="button" name="Button1" type="submit" value="Submit" /></p> </form>
If you use this script and form, there are some changes that must be made to make it work in your website:
An alternative version that is compatible with the FrontPage validation is below - but note that the user may have to press the Submit button to ensure the email address is validated.
The code for the form fields is similar to that above, but the submit button gains an onclick event code, and the <form> tag loses the onsubmit event code.
<form id="contact2" action="email-check2.htm" method="get" name="contact2"> <p><label for="email3">Email</label><input name="email1" id="email3" onchange="compFields(2)" type="text" /></p> <p><label for="email4">Retype Email</label><input name="email2" id="email4" onchange="compFields(2)" type="text" /></p> <p><input name="Button2" type="submit" value="Submit" onclick="return chkvals(3)"/></p> </form>
Again, the resulting querystring is reproduced here:
fl=2009011400