- javascript中,email正则表达式
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>02-dom中的事件</title>
<style>
</style>
<script type="text/javascript">
//如果检验不符合规则,拦截表单的提交
function fun1(){
var flag=true;
if(!check_name()){
flag=false;
}
if(!check_email()){
flag=false;
}
alert(flag);
return flag;
}
function check_name(){
//1:获得文本输入框中的内容
//var userName=document.getElementsByName("userName")[0];
var userName=document.form1.userName;
//DHTML属性
var name=userName.value;
//2:定义正则表达式对象
var reg=/^[a-zA-Z][a-zA-Z0-9_]{5,9}$/g
//3:校验
if(!reg.test(name)){
//校验失败
//alert("用户名填写错误");
addError(userName,"用户名填写错误");
return false;
}else{
removeError(userName);
return true;
}
}
function check_email(){
//DHTML属性,以“name”为准,一层一层往下写
//var email=document.form1.eMail.value;
var userEmail=document.form1.eMail;
var email=userEmail.value;
var reg=/^([a-z0-9_\.-]+)@([\da-z\.]+)\.([a-z\.]{2,6})$/g;
if(!reg.test(email)){
//alert("邮箱填写错误");
addError(userEmail,"邮箱填写错误");
return false;
}else{
removeError(userEmail);
return true;
}
}
function addError(where,what){
//where.nextSibling.innerHTML=what;
where.nextSibling.innerHTML=what;
}
function removeError(where){
where.nextSibling.innerHTML="";
}
</script>
</head>
<body>
<form action="#" name="form1" onsubmit="return fun1();">
<table border="1" width="30%">
<tr>
<th colspan="2" align="center">
用户注册
</th>
</tr>
<tr>
<td>用户名</td>
<!-- 焦点校验 -->
<td><input type="text" name="userName" onblur="check_name();"/><font color="red"></font></td>
</tr>
<tr>
<td>邮 箱</td>
<td><input type="text" name="eMail" onblur="check_email();"/><font color="red"></font></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="submit" value="提交" /></td>
</tr>
</table>
</form>
</body>
</html>