一、表单基本验证技术
二、定义正则表达式
- var reg=/表达式/附加参数
- var reg=new RegExp(“表达式”,“附加参数”)
三、表达式的模式
- var reg=/china/;
var reg=/abc8/; - var reg=/^\w+KaTeX parse error: Undefined control sequence: \w at position 14: /; var reg=/^\̲w̲+@\w+.[a-zA-Z]{…/;
四、表单验证基本使用-if
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<form action="success.html" onsubmit="return checkName()">
<div>
<label>
账号:<input id="name" type="text" />
</label>
</div>
<div>
<label>
密码:<input id="pwd" type="passwordh" />
</label>
</div>
<div>
<label>
确认密码:<input id="pwd" type="passwordh" />
</label>
</div>
<div>
<label>
邮箱:<input type="text" id="email"/>
</label>
</div>
<button type="submit">注册</button>
<button type="reset">重置</button>
</form>
</body>
<script type="text/javascript">
function $(id){
return document.getElementById(id);
}
function checkName(){
var name=$("name").value;
if(""==name){
alert("账号不能为空");
return false;
}else{
if(name.length<6||name.length>10){
alert("账号长度在6~10之间");
return false;
}
}
var pwd=$("pwd").value;
if(""==pwd){
alert("密码不能为空");
return false;
}
var myEmail=$("email").value;
if(""==myEmail){
alert("邮箱不能为空");
return false;
}else{
var e1=myEmail.indexOf("@");
var e2=myEmail.indexOf(".");
if(e1==-1||e2==-1){
alert("少了@或者.");
return false;
}else{
if(e1>e2){
alert("@要在.前面");
return false;
}
}
}
}
</script>
</html>
五、表单验证-正则表达式
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form action="success.html" onsubmit="return checkAll()">
<div>
<label>
账号:<input id="name" type="text" onkeyup="checkName()"/>
<span style="color: red;" id="sname"></span>
</label>
</div>
<div>
<label>
密码:<input id="pwd" type="passwordh" onkeyup="checkPwd() />
<span style="color: red;" id="spwd"></span>
</label>
</div>
<button type="submit">注册</button>
<button type="reset">重置</button>
</form>
</body>
<script type="text/x-javascript">
function $(id){
return document.getElementById(id);
}
function checkName(){
var name=$("name").value;
var reg=/^\w{6,10}$/;
if(!reg.test(name)){
$("sname").innerHTML="账号不符合规则";
return false;
}else{
$("sname").innerHTML="";
return true;
}
}
function checkPwd(){
var pwd=$("pwd").value;
var reg=/^[0~9]{6}$/;
if(!reg.test(pwd)){
$("spwd").innerHTML="密码不符合规则";
return false;
}else{
$("spwd").innerHTML="";
return true;
}
}
function checkAll(){
if(!checkName()||!checkPwd()){
return false;
}else{
return true;
}
}
</script>
</html>