2019独角兽企业重金招聘Python工程师标准>>>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!--需求:表单校验
思路:1 写好表单框架
2 用js分别写好每个表单功能的校验的方法,
3 把所有的方法封装到一起
-->
<script type="text/javascript">
//性提高代码的复用
function check(name,id,regex,truecode,falsecode){
var flag=false;
var val =document.getElementsByName(name)[0].value;
var spannode=document.getElementById(id);
if(regex.test(val)){
spannode.innerHTML=truecode.fontcolor("green");
flag=true;
}else{
spannode.innerHTML=falsecode.fontcolor("red");
}
return flag;
}
//校验用户名
function checkuser(){
var useregex =new RegExp("^[a-zA-Z]{4}$");
return check("usename","userspan",useregex,"用户名正确","用户名错误");
}
//校验密码
function checkpsw(){
var pswregex=new RegExp("^[0-9]{4}$");
return check("psw","pswspan",pswregex,"密码正确","密码错误");
}
//校验确认密码
function checkpsw2(){
var psw2flag=false;
var psw2name=document.getElementsByName("psw2")[0];
var pswname=document.getElementsByName("psw")[0];
var psw2val=psw2name.value;
var pswval=pswname.value;
var psw2spannode=document.getElementById("psw2span");
if(psw2val==pswval){
psw2spannode.innerHTML="确认密码正确".fontcolor("green");
psw2flag=true;
}else{
psw2spannode.innerHTML="确认密码错误".fontcolor("red");
}
return psw2flag;
}
//校验性别
function checksex(){
var sexflag=false;
var sexnode=document.getElementsByName("sex");
for(var x=0;x<sexnode.length;x++){
if(sexnode[x].checked){
sexflag=true;
break;
}
}
if(!sexflag){
var sexspannode=document.getElementById("sexspan");
sexspannode.innerHTML="请选择性别".fontcolor("red");
}
return sexflag;
}
//校验下拉菜单
function checkselect(){
var selectflag=false;
var menunode =document.getElementsByName("country")[0];
var menu_options=menunode.options;
var menuspannode=document.getElementById("menuspan");
if(menu_options[menunode.selectedIndex].value=="none"){
menuspannode.innerHTML="请选择国家".fontcolor("red");
}else{
selectflag=true;
}
return selectflag;
}
//校验表单
function checkform(){
if(checkuser()&&checkpsw()&&checkpsw2()&&checksex()&&checkselect()){
return true;
}else{
return false;
}
}
</script>
<form id="formid" οnsubmit="return checkform()">
用户名称:<input type="text" name="usename" οnblur="checkuser()"/><span id="userspan"></span><br/>
输入密码:<input type="password" name="psw" οnblur="checkpsw()"/><span id="pswspan"></span><br/>
确认密码:<input type="password" name="psw2" οnblur="checkpsw2()"/><span id="psw2span"></span><br/>
选择性别:<input type="radio" name="sex" value="nan"/>男 <input type="radio" name="sex" value="nv"/>女<span id="sexspan"></span><br/>
选择国家:<select name="country" οnchange="checkselect()">
<option value="none">选择国家</option>
<option value="cn">中国</option>
<option value="en">英国</option>
</select><span id="menuspan"></span><br/>
<input type="submit" value="提交"/><input type="reset" value="重置"/>
<!-- <input type="button" value="提交按钮" οnclick="checkform()"/> -->
</form>
</body>
</html>