初学javascript,利用正则表达式实现简单的姓名与邮箱校验功能,然后提交
<html >
<head>
<script type="text/javascript">
//姓名的方法
function checkName(){
var inputNode = document.getElementById("userName");
var spanNode = document.getElementById("userId");
var content = inputNode.value;
//编写姓名的正则
var reg = /^[a-z][a-z0-9]{5}$/i;
if(reg.test(content)){
spanNode.innerHTML = ("正确").fontcolor("green");
return true;
}else{
spanNode.innerHTML = ("错误").fontcolor("red");
return false;
}
}
//邮箱的方法
function checkEmail(){
var email = document.getElementById("email").value
var spanNode = document.getElementById("emailSpan");
//编写邮箱的正则
var reg = /^[a-z0-9]\w+@[a-z0-9]+(\.[a-z]{2,3}){1,2}$/i;
if(reg.test(email)){
spanNode.innerHTML = "正确".fontcolor("green");
return true;
}else{
spanNode.innerHTML = "错误".fontcolor("red");
return false;
}
}
//提交表单的时候会触发onsubmit方法
function checkAll(){
var userName = checkName();
var email = checkEmail();
if(userName&&email){
return true;
}else{
return false;
}
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>正则表达式</title>
</head>
<body >
<form action="success.html" method="get" onsubmit="return checkAll()">
<table border="1px" width="50%" align="center" cellspacing="0px" cellpadding="3px">
<tr>
<td width="25%">姓名: </td>
<td >
<input type="text" name = "userName" id="userName" onBlur="checkName()"/>
<span id="userId"></span>
</td>
</tr>
<tr>
<td>密码:</td>
<td>
<input type="password" name = "pwd" id="pwd" onBlur="checkPass()"/>
<span id = "passId"></span>
</td>
</tr>
<tr>
<td>确认密码:</td>
<td>
<input type="password" name = "ensurepwd" id="ensurepwd" onBlur="ensurePass()"/>
<span id = "ensure"></span>
</td>
</tr>
<tr>
<td>邮箱:</td>
<td>
<input type="text" name = "email" id="email" onBlur="checkEmail()"/>
<span id = "emailSpan"></span>
</td>
</tr>
<tr>
<td>性别:</td>
<td>
<input type="radio" checked = "true" name = "gender" id="male" vaue = "male" />男
<input type="radio" name = "gender" id="female" vaue = "female" />女
<span id = "passId"></span>
</td>
</tr>
<tr>
<td>爱好</td>
<td></td>
</tr>
<tr>
<td>城市</td>
<td></td>
</tr>
<tr>
<td>自我介绍</td>
<td></td>
</tr>
<tr>
<td colspan="2" align = "center"><input type = "submit" value = "提交查询" /></td>
</tr>
</table>
</body>
</html>
form的onsubmit事件,表单提交前验证
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>提交数据</title>
</head>
<body>
<h1><font color="#FF0000">**恭喜你,提交数据成功**</font></h1>
</body>
</html>
效果如下图:
如果输入的姓名和邮箱格式和正则表达式 不匹配,则在提交查询时显示错误,提交不了
如果姓名和邮箱格式输入正确,则显示正确,点击提交查询,数据就提交成功,弹出以下页面: