JavaScript对表单验证的例子

时间:2022-11-06 14:26:46
案例:

姓名:要求输入汉字

需要用到正则表达式 /^[\u4e00-\u9fa5]$/

正则表达式是一种匹配模式串的方法 这个我们会有专门的讲解


年龄:输入数字

爱好: 爬山 游泳 网球 乒乓球

至少选择一个

密码:输入两次,两次必须一致,且密码长度必须大于8

备注:用textarea


在JavaScript 定义函数用function定义变量用 var

<span style="color:#000000;"><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script type="text/javascript" src="1.js"></script>
</head>

<body>
<form>
输入姓名<input type="text" name="xm"><br />
年龄<input type="text" name="nn"><br />
爱好:<input type="checkbox" name="ah">游泳<input type="checkbox" name="ah">篮球
<input type="checkbox" name="ah">足球<input type="checkbox" name="ah">跑步<br />
密码:<input type="password" name="mm"><br />
重复密码:<input type="password" name="cfmm"><br />
备注<textarea name="bz" cols="10" rows="4"></textarea><br />
<input type="button" value="问候" onclick="checkit()">
</form>
</body>
</html></span>
// JavaScript Documentfunction checkit(){//var reName = RegExp("^[\u4e00-\u9fa5]+$");var reName = /^[\u4e00-\u9fa5]+$/;if(!reName.test(document.forms[0].xm.value)){alert("姓名必须输入中文!");return;}var reAge = RegExp("^[1-9][0-9]?$");if(!reAge.test(document.forms[0].nn.value)){alert("年龄输入错误!");return;}var flag = false;for(var i=0; i<document.forms[0].ah.length; i++){if(document.forms[0].ah[i].checked){flag=true;break;}}if(!flag){alert("至少选一个爱好!");return;}if(document.forms[0].mm.value.length<9){alert("密码长度必须大于8!");document.forms[0].mm.focus();return;}if(document.forms[0].cfmm.value!=document.forms[0].mm.value){alert("重复密码输入错误,请重新输入!");document.forms[0].cfmm.focus();return;}if(document.forms[0].bz.value==""){alert("备注不能为空!");}}

JavaScript对表单验证的例子JavaScript对表单验证的例子JavaScript对表单验证的例子JavaScript对表单验证的例子JavaScript对表单验证的例子JavaScript对表单验证的例子