check email address match in form (javascript validation)

jecommera
jecommera used Ask the Experts™
on
Hi,

Does anyone have any sample code to validate that two email entries in a form match using javascript?

thanks,
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Dave BaldwinFixer of Problems
Most Valuable Expert 2014

Commented:
Try this.
<html>
<head>
<script type="text/javascript">
function chkstr()
{
var Eml1=document.getElementById("eml1").value;
var Eml2=document.getElementById("eml2").value;

if(Eml1 != Eml2) {
	alert("Email addresses don't match.");
	}
}
</script>
</head>
<body>
<h1>js-strcmp.html</h1>
<form action="#" method="get" onsubmit="return chkstr();">
<input type="text" name="eml1" id="eml1" value="Email 1" /><br />
<input type="text" name="eml2" id="eml2" value="Email 2" /><br />
<input type="submit" value="Submit" />
</form>

</body>
</html>

Open in new window

you could also use compare validator (in ASP.NET) if you dont wish to use javascript

Author

Commented:
Thanks a million. Almost there.

If I enter two different emails. It alerts however it still submits the form.

Author

Commented:
how do I stop it submitting the form when email error is detected?
Fixer of Problems
Most Valuable Expert 2014
Commented:
I added a 'return false' to the check.
<html>
<head>
<script type="text/javascript">
function chkstr()
{
var Eml1=document.getElementById("eml1").value;
var Eml2=document.getElementById("eml2").value;

if(Eml1 != Eml2) {
	alert("Email addresses don't match.");
	return false;
	}
}
</script>
</head>
<body>
<h1>js-strcmp.html</h1>
<form action="#" method="get" onsubmit="return chkstr();">
<input type="text" name="eml1" id="eml1" value="Email 1" /><br />
<input type="text" name="eml2" id="eml2" value="Email 2" /><br />
<input type="submit" value="Submit" />
</form>

</body>
</html>

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial