正在学习JavaScript,所以就将自己写的小例子上传上来,其实上网搜一下,有大把的JavaScript的验证实例,要自己慢慢研究,自己动手写一下,自己很粗心,希望以后要细心点!
贴上代码:
<!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=gb2312" />
<style>
.denglu{
width:450px;
}
.denglu li{
list-style:none;
}
.yanse{
color:red;
}
.blank_bg {
background-color:#CC0000;
color:#FFFF00;
border-width:0px;
}
</style>
<script language="javascript">
function ger_code(code_length){ //动态生成验证码
var rand_aa="";
var code=new Array("0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J",
"K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h",
"i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z");
var code_Num=code.length;
for(i=0;i<code_length;i++){
var ran_ss=parseInt(Math.random()*code_Num);
rand_aa+=String(code[ran_ss]);
}
document.write("<input type=text name=check_code size="+code_length+" value="+rand_aa+" class=blank_bg maxsize=4 readonly=true>");
}
function subTest(){
var name = document.testForm.userName.value;
var pass = document.testForm.password.value;
var check = document.testForm.check.value;
var check_code = document.testForm.check_code.value;
if(name.length > 10 || name.length < 4){
alert("用户名长度必须大于等于4,小于等于10");
testFrom.userName.focus();
return false;
}
if(isFirst()){
alert("用户名头字母不能为数字或者_");
testForm.userName.focus();
return false;
}
if(isSpace()){
alert("用户名只能包含字母,数字");
testForm.userName.focus();
return false;
}
if(pass.length < 1){
alert("请输入密码");
testForm.password.focus();
return false;
}
if(check!= check_code){
alert("验证码不正确");
testForm.check.focus();
return false;
}
else {alert('注册成功');}
return true;
}
function isSpace(){
var name = document.testForm.userName.value.split("");
for(i = 0; i < name.length; i++){
if(name[i] == " "){
return true;
}else if( !((name[i] < "z" && name[i] > "a") || (name[i] < "Z" && name[i] > "A")
|| (name[i] < "9" && name[i] > "0"))){
return true;
}
}
return false;
}
function isFirst(){
var name = document.testForm.userName.value.split("");
if(name[0] < "9" && name[0] > "0" ){
return true;
}
return false;
}
</script>
<title>无标题文档</title>
</head>
<body>
<div class="denglu" >
<form name = "testForm" method = "post" onSubmit="subTest()">
<li><span>用户名:</span><span><input name="userName" type="text" /></span><span class="yanse">*不可以为空</span></li>
<li><span>密 码:</span><span><input name="password" type="text" /></span><span class="yanse">*不可以为空</span></li>
<li><span>验证码:</span><span><input name="check" type="text" /></span><span class="yanse">*不可以为空<script language = "JavaScript">ger_code(4);</script></span></li>
<li><span><input name="submit" type="submit" value="提交" /></span><span><input name="reset" type="reset" value="重置"/></span></li>
</form>
</div>
</body>
</html>
主要验证用户名是否为空,首个字符不能是数字,只能包含数字和字母
验证密码是否为空
验证码是否输入正确