Dsadsadsa Sdasdasda
Dsadsadsa Sdasdasda

Reputation: 45

Why does my form validation using JavaScript not prevent the form from being sent?

i have this small javascript to check if the email is valid, i check client side, couse its not 100% important that the mail is valid, and i dont want to re-direct the user just to check.

The issue is that the popup does apear, but the users values are still inserted

  <script>
function popup()
{  

    var email = document.getElementById("email").value;
    var atpos=email.indexOf("@");
    var dotpos=email.lastIndexOf(".");

if (document.getElementById("email").value == "") {

    alert("Enter an email");
    return false;

 }
else if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length) {

    alert("The email is not valid");
    return false;

 }
else
    window.location = "email.php";
    return true;
}
   </script>

and here is the HTML form

 <form action="email.php" accept-charset="UTF-8" class="signup_form" id="signup_form" method="post">


<input class="txt accent-color colorize_border-color required" id="email" name="email" placeholder="Indtast E-mail her" data-label-text="Email" type="email">

<input class="submit button big btn" id="submit_button" name="submit" value="Deltag nu!" onclick="return popup()"  type="submit">

</form>

if i remove "type submit" it works, but i dont get the values with $_POST on the next page, they are null.

Any way to get around this?

Upvotes: 2

Views: 195

Answers (1)

mplungjan
mplungjan

Reputation: 178403

Canonical

window.onload=function() {
  document.getElementById(("signup_form").onsubmit=function() {
    var email = document.getElementById("email").value;
    var atpos=email.indexOf("@");
    var dotpos=email.lastIndexOf(".");

    if (document.getElementById("email").value == "") {
      alert("Enter an email");
      return false;
    }
    if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length) {
      alert("The email is not valid");
      return false;
    }
    return true;
  }
 }

using

<form action="email.php" accept-charset="UTF-8" class="signup_form" id="signup_form" method="post">
  <input class="txt accent-color colorize_border-color required" id="email" name="email" placeholder="Indtast E-mail her" data-label-text="Email" type="email">
  <input class="submit button big btn" id="submit_button" name="submit" value="Deltag nu!"   type="submit">
</form>

Upvotes: 3

Related Questions