表单验证
邮箱验证一般使用正则表达式:
【1】^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$
【2】/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
在输入控件失去焦点时进行验证:
- 失去焦点的事件为
onblur
- 获得焦点的事件为
onfocus
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<link href="Untitled-1.css" rel="stylesheet" type="text/css">
</head>
<body>
<form id='form1' name="form1" action='Untitled-2.html' method="post" onSubmit="return validateForm()">
请输入Email:<input type='text' id="emailInput" name='emailInput' class='init'></input>
<input type='submit' value="提交" id="submit" name="submit"></input>
</form>
<script type="text/javascript">
function validateEmail(){
var emailInput = document.getElementById('emailInput');
var reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
if(reg.test(emailInput.value)){
emailInput.className = 'right';
return true;
}
else{
emailInput.className = 'wrong';
return false;
}
}
function validateForm(){
return validateEmail();
}
window.onload = function(){
document.getElementById('emailInput').addEventListener('blur',validateEmail,false);
document.getElementById('form1').addEventListener('submit',validateForm,false);
}
</script>
</body>
</html>
css文件下附:
@charset "utf-8";
/* CSS Document */
.init{
border-color:#000000;
font-size:20px;
border-width:3px;
}
.wrong{
border-color:#FF0000;
font-size:20px;
border-width:3px;
}
.right{
border-color:#00FF00;
font-size:20px;
border-width:3px;
}