0

I have a problem with the validation script of my php form to send an email, and although it works very well to validate the form, when the user clicks on the "accept" button of the alert, the script does not block the action, and the form is sent anyway...

What am I doing wrong?

Thanks in advance!

HTML:

<div id="form">
 <section>
  <form action="send.php" method="post" accept-charset='UTF-8'>
  <label for="email"></label>
  <input id="email" type="email" name="email" maxlength="50">
  <input type="hidden" name="privacy" value="blahblahblah"/>

  <input id="submit" type="submit" name="submit" value="SEND" onclick="validate(this);">

  </div>
  </form>
 </section>
</div>

SCRIPT (validation):

function validate () {
    var email;
    email = document.getElementById("email").value;
    expresion = /\w+@\w+\.+\w/;

if(email === "") {
    alert("You cannot submit this request. You must give us an email");
    return false;
    }

else if (email.length>50) {
    alert("The maximum for email is 50 characters");
    return false;
    }

else if (!expresion.test(email)) {
    alert("Check your information. The email format is not valid");
    return false;
    }
}
2
  • alert will freeze the JS engine. Better include this in some kind of modal Commented Nov 6, 2019 at 19:31
  • @karthick But in other cases works perfectly for me, and using the native alert of the visitor's browser. Now I don't know why it doesn't work. Tested in Opera, Firefox and Chrome Commented Nov 6, 2019 at 19:35

1 Answer 1

1

Change the event to onsubmit and put it on the form.

function validate () {
    var email;
    email = document.getElementById("email").value;
    expresion = /\w+@\w+\.+\w/;

if(email === "") {
    alert("You cannot submit this request. You must give us an email");
    return false;
    }

else if (email.length>50) {
    alert("The maximum for email is 50 characters");
    return false;
    }

else if (!expresion.test(email)) {
    alert("Check your information. The email format is not valid");
    return false;
    }
  console.log('passed!');
}
<div id="form">
    <section>
        <form action="" method="post" accept-charset='UTF-8' onsubmit="return validate(this);">
            <label for="email"></label>
            <input id="email" type="email" name="email" maxlength="50">
            <input type="hidden" name="privacy" value="blahblahblah"/>

            <input id="submit" type="submit" name="submit" value="SEND">
        </form>
    </section>
</div>

Sign up to request clarification or add additional context in comments.

Comments

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.