可以根据正则表达式判断某个值是否是邮箱格式:
邮箱正则表达式:
var RegEmail = /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/JS验证代码:
var userEmail="[email protected]"if(RegEmail.test(userEmail))//如果返回true,表示userEmail符合邮箱格式
{}
else
{}
你可以试试!
<form action="">输入:<input type="text" name="mazey" id="mazey" placeholder="请输入邮箱">
<input type="button" value="验证" onclick="check()">
</form>
<script>
function check(){
var reg = new RegExp("^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$") //正则表达式
var obj = document.getElementById("mazey") //要验证的对象
if(obj.value === ""){ //输入不能为空
alert("输入不能为空!")
return false
}else if(!reg.test(obj.value)){ //正则验证不通过,格式不对
alert("验证不通过!")
return false
}else{
alert("通过!")
return true
}
}
</script>
<html><head>
<script type="text/javascript">
function validate()
{
var ok=true,un,pw1,pw2,el,ch0
var r = /^([0-9A-Za-z\-_\.]+)@([0-9a-z]+\.[a-z]{2,3}(\.[a-z]{2})?)$/g
if(""==(un=document.f.user.value))
{
alert("用户名不能为空!")
document.f.user.focus()
ok=false
}
else if(""==(pw1=document.f.password1.value))
{
alert("密码不能为空!")
document.f.password1.focus()
ok=false
}
else if(""==(pw2=document.f.password2.value))
{
alert("重复密码不能为空!")
document.f.password2.focus()
ok=false
}
else if(""==(el=document.f.email.value))
{
alert("邮箱不能为空!")
document.f.email.focus()
ok=false
}
if(ok)
{
if(!(un.length>=6 &&un.length<=20))
{
alert("用户名长度必须大于等于6小于等于20!")
document.f.user.focus()
ok=false
}
else
{
ch0=un.charAt(0).toLowerCase()
if(!(ch0>="a" &&ch0<="z"))
{
alert("用户名必须以字母开头!")
document.f.user.focus()
ok=false
}
else if(pw1!=pw2)
{
alert("重复密码与密码必须相同!")
document.f.password2.focus()
ok=false
}
else if(!r.test(el))
{
alert("不是有效的邮箱地址!")
document.f.email.focus()
ok=false
}
}
}
if(ok)
{
alert("恭喜你,通过了有效性验证!")
}
}
</script>
</head>
<body>
<form name="f">
用户名:<input type="text" name="user" /><br /><br />
密码:<input type="text" name="password1" /><br /><br />
重复密码:<input type="text" name="password2" /><br /><br />
邮箱:<input type="text" name="email" /><br /><br />
<input type="button" value="验证" onclick="validate()" />
</form>
</body>
</html>