2

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?

1
  • 5
    Also use onsubmit of the form instead of onclick of the button. Use onsubmit="return validate(this)" and return false from the function to stop submission and try to allow Commented Mar 9, 2013 at 15:50

1 Answer 1

3

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Clarification for the OP: The validation function must be tied to the form's onsubmit event because it is this event that must receive return false to stop the form submission.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.