<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=gb2312″ />
<title>表单验证</title>
<script language=”javascript” src=”include/form.js”>
</script>
</head>
<body><form action=”#” method=”post” name=”form” id=”form”>
姓 名:<input name=”username” type=”text” id=”username” />字母、数字、下划线<br />
密 码:<input name=”password” type=”password” id=”password” /><br />
密码确认:<input name=”password2″ type=”password” id=”password2″ /><br />
生 日:<input name=”birthday” type=”text” id=”birthday” />20100712<br />
E-mail :<input name=”email” type=”text” id=”email” /><br />
<input type=”reset” value=”重写” />
<input type =”submit” value =”提交” onclick =”return CheckForm();”>
</form>
</body>
其中需要javas代码存储的form.js页面,代码如下:
<!–
function CheckForm()
{
if (document.form.username.value.length == 0)//*********************************姓名验证
{
alert(“请输入姓名!”);
document.form.username.focus();
return false;
}
else if(!Testusername(document.form.username.value))
{
//document.write(document.form.username.value);
alert(“姓名格式错误!”);
return false;
}
else if(document.form.password.value.length == 0)//****************************密码验证
{
alert(“密码不能为空”);
document.form.username.focus();
return false;
}
else if(!Testpassword(document.form.password.value,document.form.password2.value))
{
//document.write(document.form.password.value);
alert(“两次密码不相同”);
document.form.password2.focus();
return false;
}
else if(!Testday(document.form.birthday.value))//**********************生日验证
{
//document.write(document.form.birthday.value);
alert(“生日格式错误”);
document.form.birthday.focus();
return false;
}
else if(!Testemail(document.form.email.value))//****************邮箱验证
{
alert(“邮箱格式错误”);
document.form.birthday.focus();
return false;
}
return true;
}
function Testusername(struesrname)//*************************字母数字下划线
{
var pattern = /[a-zA-Z0-9_]/;
if(pattern.test(struesrname))
return true;
else
return false;
}
function Testpassword(str_ps1,str_ps2)//********************两次密码相同
{
if(str_ps1==str_ps2)
return true;
else
return false;
}
function Testday(str)//*************************************格式为20100712
{
var pattern= /[0-9]{8}/;
if(pattern.test(str))
return true;
else
return false;
}
function Testemail(str_email)//************************格式是:以字母数字下划线开头然后是任意字符和@下面是字母数字和.和2到3位字母数字结束
{
var pattern=/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(pattern.test(str_email))
return true;
else
return false;
}
–>
注:也可以使用跳转页面使用PHP验证(简单举例)
$flag=true;
if(!ereg(“[a-zA-Z0-9_]”,$_POST[“username”]))
{
echo “姓名格式不正确<br />”;
$flag=false;
}
if(!ereg(“[0-9]{8}”,$_POST[“birthday”]))
{
echo “生日日期不正确<br />”;
$flag=false;
}
if($flag)
{
echo $_POST[“username”];
echo $_POST[“birthday”];
}
本例只是一个简单的javascript验证表单,希望对你有所帮助
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有