I am completely new to javascript .
I have tried using javascript to validate the format of email when the user enters an email id . The following javascript code works perfectly fine for me . The code simply doesn't allow a form to be submitted if the user enters a wrong email format . It displays an error message and focuses on the textbox which is used to enter the email, if the user enters a wrong email format .
Here is the code :
<!doctype html>
<html>
<head>
</head>
<body>
<form name="frmregistration" action ="" method="post" enctype="multipart/form-data">
<table align="center">
<tr>
<td>Email</td>
<td><input type="text" maxlength='100' name="txtemail" id="idemail"></td>
<td><div id="iddivemail"></td>
</tr>
<tr>
<td><input type="submit" value="register" id="idsubmit" onclick="return validateEmail()"></td>
</tr>
</table>
</form>
<script >
<!-- document.getElementById("idsubmit").addEventListener("click", validateEmail) -->
function validateEmail()
{
var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var mail = document.frmregistration.txtemail.value;
var res = mail.match(mailformat);
if (res == null) {
document.getElementById("iddivemail").innerHTML = "invalid email";
document.frmregistration.txtemail.focus();
return false;
}
}
</script>
</body>
</html>
However, after going through several questions on Stack Overflow and other articles on the internet, I have realized the importance of unobtrusive javascript coding, where html markup, css ,and javascript are kept seperate .I have also realized the importance of progressive enhancement, where javascript is not completely relied upon. In such cases applications are be designed keeping in mind that the user may have javascript turned off, and javascript should be used to improve the user's experience .
Some of the links that I have followed are : http://www.onlinetools.org/articles/unobtrusivejavascript/chapter1.html http://www.ibm.com/developerworks/library/wa-aj-unobtrusive/
Now , when I tried using addEventListener to add the function to the click event of the submit button,it doesn't work for me .The form gets submitted even if I return false from the function . The following code doesn't work :
document.getElementById("idsubmit").addEventListener("click", validateEmail)
Have I done something seriously wrong here or have I completely misunderstood the concept?
How do I use the same code "return(validateInput())" in an unobtrusive way ?
I have gone through the duplicate questions on using javascript code in the onclick event of submit button on Stack Overflow, but I couldn't find an answer to this specific problem.
Any help will be appreciated.