如何在JavaScript中验证电子邮件地址?
html代码:
<body>
<form>
<p>Enter an email address:</p>
<input id='email'>
<button type='button' id='validate'>Validate!</button>
</form>
<h2 id='result'></h2>
</body>
JavaScript代码:
<script type="text/javascript">
$(function(){
function validateEmail(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);
}
function validate() {
console.log(999)
var $result = $("#result");
var email = $("#email").val();
$result.text("");
if (validateEmail(email)) {
$result.text(email + " is valid :)");
$result.css("color", "green");
} else {
$result.text(email + " is not valid :(");
$result.css("color", "red");
}
return false;
}
$("#validate").bind("click", validate);
})
</script>