I am trying to validate email in a form input by a button click. Here is the code:
function ValidateEmail(inputText) {
var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (inputText.value.match(mailformat)) {
document.form1.coemail.focus();
return true;
} else {
alert('You have entered an invalid email address!Enter again');
document.getElementById('form1').reset();
return false;
}
}
<button class="btn btn-primary nextBtn btn-lg pull-right" type="button"onClick="ValidateEmail(document.form1.coemail)">Next</button>
On clicking the Next button I get an alert message correctly but after that it redirects to next page instead of resetting the current one. On inspecting element in chrome's console,I found this error: Uncaught TypeError: Cannot read property 'reset' of null
Where am I wrong here ?
Add id
to your form:
<form id="form1" role="form" name="form1" action="reg_employer.php" method="post">
or
Try:
function ValidateEmail(inputText)
{
var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(inputText.value.match(mailformat))
{
document.form1.coemail.focus();
return true;
}
else
{
alert("You have entered an invalid email address!Enter again");
document.form1.reset(); //<== change this line, use form name
return false;
}
}
Apparently I didn't have a form id in
<form id="form1" role="form" name="form1" action="reg_employer.php" method="post">
Addition of a form id resolved the issue.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.