使用javascript检查有效的电子邮件

时间:2013-02-05 20:09:20

标签: javascript jquery

我可以检查空字段但是如何检查有效的电子邮件检查正则表达式?这是我到目前为止所拥有的

<script>
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
  {
  alert("First name must be filled out");
  return false;
  }
var y=document.forms["myForm"]["email"].value;
if (y==null || y=="")
  {
  alert("email must be filled out");
  return false;
  }
}
</script>
</head>

<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname"><br>
email: <input type="text" name="email">

<br><br>
<input type="submit" value="Submit">
</form>

2 个答案:

答案 0 :(得分:1)

您可以做的第一件事是使用HTML5 type="email" attribute.,浏览器将本机验证。但你必须总是有一个后退。

使用(找到here

/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/

作为regualar表达式:并且

var validEmailStyle = /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/
if(!validEmailStyle.test(document.forms["myForm"]["email"].value))
{
  // the user is dumb and fill in an invalid email, show a help text
  // or something like that
}​

- PeeHaa

的有效评论后进行修改

你一定不要忘记验证服务器端,如果你使用PHP,你可以使用preg_match使用相同的正则表达式

答案 1 :(得分:-1)

var pattern = /^\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i

if(!pattern.test(userinput))
{
  alert('not a valid e-mail address');
}​

只是展示一个例子,你可以找到一个更好的正则表达式模式。