Search code examples
javascriptformsemailemail-validation

Javascript - A problem with the validation of my form


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;
    }
}

Solution

  • 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>