I am currently using this HTML code:
<form onsubmit="return validateForm()" action="page.html" >
Name: <input type="text" id="name" /><br />
Email: <input type="text" id="email" /><br />
<input type="submit" value="Submit" />
</form>
But I would like to move my event handlers into my separate javascript, into the function named initiate. My javascript looks like this:
function formValidator(){
var name = document.getElementById("name");
var email = document.getElementById("email");
if(isAlphabet(name, "Fill in name"))
{
if(emailValidator(email, "Fill in email"))
{
return true;
}
}
return false;
}
function isAlphabet(elem, helpMsg)
{
var alphaExp = /^[a-zA-Z]+$/;
if(elem.value.match(alphaExp))
{
return true;
}
else
{
alert(helpMsg);
elem.focus();
return false;
}
}
function emailValidator(elem, helpMsg)
{
var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
if(elem.value.match(emailExp))
{
return true;
}
else
{
alert(helpMsg);
elem.focus();
return false;
}
}
function initiate {
// ..
}
window.onload = initiate;
So far I’ve only figured out how to write the code to redirect to the new webpage but it doesn’t check that it is a valid code. I’ve used this:
HTML
<form id="form">
Name: <input type="text" id="name" /><br />
Email: <input type="text" id="email" /><br />
<input type="submit" value="Submit" />
</form>
Javascript
document.getElementById("form").action = "page.html";
But I can’t figure out how to write so that both the .action="page.html" and the return validateForm()is working.
Your form needs an
id:Separate Javascript file:
Make sure the
validateForm()function is returning false if something didn’t validate.