La validación de correo electrónico Javascript no funciona
Frecuentes
Visto 226 veces
-5
What is wrong with my code? I can't find the solution.
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,}))$/";
var email= document.getElementById("email").value;
if (re.test(email) == false) {
document.getElementById("email").focus();
return false;
}
The double quotes caused the problem, thank you! I cant vote up because of my reputation :-(
2 Respuestas
1
Like suresh suggested, you should remove the quotes (") around your regex string. So your first line should be:
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,}))$/;
I produced a working example below:
<script>
function test()
{
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,}))$/;
var email= "test@somedomain.com";
if (re.test(email) == false) {
alert("invalid email address");
return;
}
alert("valid address");
}
</script>
<button onclick="test()">TEST</button>
Respondido 24 ago 12, 12:08
-1
Lets try this once which is working smart for me
function IsEmail(email) {
var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
if(!IsEmail(mailString)){
$("#somediv").text(" Email should be valid ");
return false;
}
Respondido 24 ago 12, 10:08
People - the question is "What is wrong with my code". It's no "how to validate email addresses". - JJJ
@jim bamboo ..remove the "" to your regex string . - user1612220
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas javascript email-validation or haz tu propia pregunta.
¿Por qué tan complicado?
see here
- diEchoTu dices us what's wrong. Do you get an error? Does it not validate correctly? Does it pass all input, or does it not pass any valid emails, or does it give false positives/negatives? - JJJ
duplicar stackoverflow.com/questions/46155/… - yogi
Holy moley! That's a complex validation you have there! - Marcos Placona
You don't need to vote up, just acepta la respuesta correcta. - JJJ