It is often required that two fields in a form are compared, for example to ensure an email address has been entered accurately.
The form below shows two fields, and uses Javascript fired by the onchange event to ensure the contents of the fields are identical.
This example also checks that the email address is in a valid format, 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.
The javascript used is:
<script type="text/javascript">
function isEmail(string) {
var regex1 = /^[\w\.\-]*[\w\.\-]+\@([a-z0-9]+[\.\-])*[a-z0-9]+\.[a-z]{2,}$/i
var regex2 = /^[\w\.\-]*[\w\.\-]+\@\[\d{1,3}\.\d{1,3}\.\d{1.3}\.\d{1,3}\]$/i
if (regex1.test(string)) { return true; }
else {
if (regex2.test(string)) { return true; }
else {
alert("Email address is not valid")
return false;
}
}
}
function chkvals(theForm) {
var df = document.forms[theForm]
if (!compFields(theForm)) return false;
if (df.email1.value == "") {
alert("Must have an email address in email field");
df.email1.focus;
return false;
}
if (df.email2.value == "") {
alert("Must have an email address in Check email field");
df.email2.focus;
return false;
}
return isEmail(df.email1.value)
}
function compFields(theForm) {
var aa,bb;
aa = document.forms[theForm].email1.value;
bb = document.forms[theForm].email2.value;
if ((aa=="") || (bb=="")) { return true; }
if (aa!=bb) {
alert("Email and check fields should match");
document.forms[theForm].email1.focus;
return false;
}
return true;
}
</script>
The form HTML is:
<form id="contact" action="email-check.htm" method="get" name="contact" onsubmit="return chkvals('contact')">
<p>Email <input class="inp" name="email1" onchange="compFields('contact')" type="text" /></p>
<p>Check Email <input class="inp" name="email2" onchange="compFields('contact')" type="text" /></p>
<p style="padding-left:3em;"><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:
<form id="contact" action="email-check.htm" method="get" name="newname" onsubmit="return chkvals('newname')"><p>Email <input class="inp" name="email1" onchange="compFields('newname')" type="text" /></p>
<p>Check Email <input class="inp" name="email2" onchange="compFields('newname')" type="text" /></p>