Javascript form validation submit errors

2019-07-16 11:31发布

From everything I've seen around the net, it appears that the following code should do the following (and this is my expectation):

  • If the email ("aid") does not match the regex, show alert message and return false
  • If the password ("pass") is blank, show alert message and return false
  • If both conditions pass validation submit the form

The Javascript is as follows:

function validate() {
var email = document.getElementById('aid').value;
var pass = document.getElementById('apw').value;        
var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;  
if (!emailPattern.test(email)) {
    alert("Not a valid email address");
    return false;
}
if (pass == null || pass == "") {
    alert("Password is blank");
    return false;   
}
return true;
}

The opening for tag is as follows:

<form action="choose.php" onsubmit="validate();" method="post">

The problem I'm having is that when the submit button is clicked, the alert message will pop up, but then choose.php is loaded in the browser. I want the script, if the error conditions are triggered, to remain on the page until both conditions are passed.

1条回答
干净又极端
2楼-- · 2019-07-16 12:16

You need to change your onSubmit to onSubmit="return validate();". This way when it returns false, the form doesn't get submitted. Right now it just calls the validate() function and continues on with submitting the form

查看更多
登录 后发表回答