最近js用的比较多,所以简单的整理下
<!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>FormVerify</title>
</head>
<script type="text/javascript">
<!--js中trim函数,去除两边的空格-->
function trim(str){ //删除左右两端的空格
return str.replace(/(^\s*)|(\s*$)/g, "");
}
function ltrim(str){ //删除左边的空格
return str.replace(/(^\s*)/g,"");
}
function rtrim(str){ //删除右边的空格
return str.replace(/(\s*$)/g,"");
}
<!--对表单提交是的验证,在onSubmit中需要return-->
function fsub(){
<!-- 表单验证,不能为空,如果为空,提示后激活当期为空的窗体-->
var name=document.getElementById("username");
//去除姓名两边空格
if(trim(name.value)==""){
alert("姓名不能为空");
name.focus();
return false;
}
<!-- 判断密码不能为少于6位,和两次密码是否相同-->
var password=document.getElementById("password");
var passworda=document.getElementById("passworda");
if(password.value.length < 6){
alert("密码不能少于6位");
return false;
}
if(password.value != passworda.value){
alert("两次密码不一致");
return false;
}
<!--对单选按钮(radio)及多个值进行校验用ElementsByName -->
var sex=document.getElementsByName("radio");
var count=0;
for(var i=0;i<sex.length;i++){
if(sex[i].checked){
count++;
}
}
if(count==0){
alert("请正确选择性别");
return false;
}
<!--对下拉列表(select)的校验-->
var category=document.getElementById("category");
//>1因为第一个是默认选中,
if(category.selectedIndex < 1){
alert("请选择下拉");
return false;
}
<!--对复选框(checkbox的校验)-->
var hobby=document.getElementsByName("hobby");
var flag=false;
for(var i=0;i<hobby.length;i++){
if(hobby[i].checked){
flag=true;
break;
}
}
if(!flag){
alert("至少选择一项爱好");
}
return flag;
}
</script>
<body>
<form id="form1" name="form1" method="post" action="" οnsubmit="return fsub()">
<table width="80%" border="1">
<tr>
<td align="right">用户名:</td>
<td><input type="text" name="username" id="username" /></td>
</tr>
<tr>
<td align="right">密码:</td>
<td><input type="password" name="password" id="password" /></td>
</tr>
<tr>
<td align="right">请确认密码:</td>
<td><input type="password" name="passworda" id="passworda" /></td>
</tr>
<tr>
<td align="right">性别:</td>
<td>男
<input type="radio" name="radio" id="man" value="man" />
女
<input type="radio" name="radio" id="women" value="women" /></td>
</tr>
<tr>
<td align="right">分类:</td>
<td>
<select name="category" id="category">
<option value="">请选择</option>
<option value="work">工作</option>
<option value="firend">朋友</option>
<option value="family">家人</option>
</select>
</td>
</tr>
<tr>
<td align="right">爱好:</td>
<td>
<input type="checkbox" name="hobby" id="hobby" value="movic"/>
电影
<input type="checkbox" name="hobby" id="hobby" value="travel"/>
旅游
<input type="checkbox" name="hobby" id="hobby" value="poker"/>
打牌
</td>
</tr>
<tr>
<td align="right">
<input type="submit" name="btnsubmit" id="btnsubmit" value="提交" />
</td>
<td><input type="reset" name="btnresult" id="btnresult" value="重置" /></td>
</tr>
</table>
</form>
</body>
</html>