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 ?
To solve the "Cannot read property 'value' of null" error, make sure you aren't accessing the value property on a null value, e.g. a non-existent DOM element. An element with the provided id does not exist in the DOM, so the getElementById method returns null .
To solve the "Cannot set property 'value' of null" error, make sure that the DOM element you are accessing exists. The error is often thrown when trying to set a property after using the getElementById() method and passing it a non-existent id. Copied! const input = document.
If the error message says "Could not read property 'id' of null" it means that the guild property exists, but it is null.
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;
}
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With