简体   繁体   中英

Unable to stop form from submitting when validating an email

I am making a simple form that takes the value from a text input, checks if all the characters that are in an email address are there and returns true or false. According to a lot of different resources, if it returns false, then the form shouldn't be submitted. However, when I test it in JS bin, it submits it. Here's the code:

 function validateEmail(x) { console.log(x); var email = x.myText.value; console.log(email); var re = /^(([^<>()\\[\\]\\\\.,;:\\s@"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@"]+)*)|(".+"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/; console.log(re.test(email)); } 
 <form name="myForm" onsubmit="return validateEmail(this)"> <input name="myText" type="text"> <input type="submit" value="Submit"> </form> 

you need to return false if the validation fails, so simply replace

console.log(re.test(email));

with

return re.test(email);

Demo

Try this:

function validateEmail(x) {
  console.log(x);
  var email = x.myText.value;
  console.log(email);
  var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
}

Change <form name="myForm" onsubmit="return validateEmail(this)">

With this <form name="myForm" onClick="return validateEmail(this)">

And function is like this

function validateEmail(x) { console.log(x); var email = x.myText.value; console.log(email); var re = your regular expression; if((re.test(email)){ document.getElementById(myForm).submit(); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM