几种常见的js表单验证

<%@ page contentType="text/html; charset=GBK"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'keydown.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">

<script type="text/javascript">
//1.验证必填
function check(){
if(document.form.username.value==""){
alert("请填写用户名");
document.form.username.focus();
return false;
}
//2.验证长度
if(document.form.password.value==""||document.form.password.value.length<6){
alert("填写不合法,密码至少为6位数");
document.form.password.focus();
return false;
}
//3.验证邮件地址
var email=document.form.email.value;
var emailreg=/^(.+)@(.+)$/;
var match=email.match(emailreg);
if(email==""||match==null){
alert('请填写合法的邮件地址');
document.form.email.focus();
return false;
}
//4.js验证只能输入数字.
//定义正则表达式部分
var test1=document.form.test1.value;
var reg1 = /^[0-9]+$/;
var matchreg1=test1.match(reg1)
if(test1==""||matchreg1==null ){
alert('填写不合法,请输入数字');
document.form.test1.focus();
return false;
}
//5.js验证只能输入字母.数字和下划线.
var test2=document.form.test2.value;
var reg2 = /^\w+$/;
var matchreg2= test2.match(reg2)
if(test2==""||matchreg2==null){
alert('填写不合法,请输入字母,数字或下划线');
document.form.test2.focus();
return false;
}
//6.js验证固定电话:只能是数字.并且有相应的格式//028-67519441 或者 0839-8777222或者 028-6545124
var reg3 = /^(\d{3,4})-(\d{7,8})/;
var test3=document.form.test3.value;
var matchreg3=test3.match(reg3);
if( test3==""||matchreg3==null ){
alert('填写不合法,请输入固定电话');
document.form.test3.focus();
return false;
}
return true;
}
</script>
</head>
<body>
<form id="form" name="form" method="post" action="" onSubmit="return check()">
<table width="414" height="169" border="1">
<tr>
<td width="125">
验证必填: </td>
<td width="273">
<input type="text" name="username" value=""/>
</td>
</tr>
<tr>
<td>
验证长度:
</td>
<td>
<input type="text" name="password" value=""/>
</td>
</tr>
<tr>
<td>
验证邮件:
</td>
<td>
<input type="text" name="email" value=""/>
</td>
</tr>

<tr>
<td>
验证只能输入数字:
</td>
<td>
<input type="text" name="test1" value=""/>
</td>
</tr>
<tr>
<td>
验证只能输入字母,数字,下划线:
</td>
<td>
<input type="text" name="test2" value=""/>
</td>
</tr>
<tr>
<td>
验证输入固话:
</td>
<td>
<input type="text" name="test3" value=""/>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" name="Submit" value="保存" />
<input type="reset" name="Submit2" value="重置" />
</td>
</tr>
</table>
</form>
</body>
<html>

你可能感兴趣的:(表单验证)