I needed to write a quick JavaScript that could check if two email addresses were the same or not today. As it’s so simple, I thought I’d share it.
Firstly we put the following JavaScript into a script
tag.
function compareEmails(myForm) { if (myForm.email.value != myForm.email2.value) { alert("Your email addresses don't match. Please double check"); return false; } else { return true; } }
It takes a form, and compares the values of the fields called email
and email2
. If they are the same it returns true
which lets the form submit normally.
However, if email
and email2
are different it brings up an alert box telling our submitter the values are different, and returns false. Returning false means the script won’t submit to the script specified in the action
parameter so the user has to confirm their email address again.
The following HTML code gives an example of the scripts use.
<form action="dosomething.pl" onSubmit="compareEmails(this);"> Email :<input type="text" name="email" /> <br /> Verify Email: <input type="text" name="email2" /> <br /> <input type="submit" /> </form>
Of course the code can be used to compare any fields and not just email addresses. All you need to do is to change the field names in the JavaScript.
Enjoy!