3

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.

3
  • Side note, here's a better RegEx for ya: ex-parrot.com/~pdw/Mail-RFC822-Address.html Commented Nov 28, 2012 at 0:05
  • There are valid e–mail addresses that will fail the e–mail test. Better to just let users enter whatever they want and test it by sending an e–mail. Oh, and the function doesn't have to return true, any value other than false will let the form submit. Commented Nov 28, 2012 at 0:10
  • I'm aware of the shortcomings with the above RegEx (and using RegEx to validate email in general), but these aren't really concerns for this project. Thanks for the links/input though. Commented Nov 28, 2012 at 0:35

1 Answer 1

5

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

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.