一。表单常用事件
有三个,onsubmit(表单提交)事件,onfocus(获得焦点)事件,onblur(失去焦点)事件。
1. onsubmit事件作用:组织或者允许表单的提交。
<form action="" method="post" onsubmit="return false">
renturn 值为false时,无法提交。表单验证的实质:一开始设置为false,只有当所有验证都通过之后,才把它的值改为true,这样才能提交表单。代码如下:
<form action="" method="post" onsubmit="return checkForm()">
//checkForm伪代码形式
function checkForm(){
if('所有验证通过'){
return true;
}else{
return false;
}
}
2. onfocus事件(点击输入框时触发): 常用于用户点击输入框时清空输入框的内容,并且改变输入框的样式,让用户清晰的看到当前正在哪一个输入框中进行输入。
3. onblur事件实在输入框中的内容完成之后,鼠标离开是这个输入框时触发的事件。常利用这个事件来进行一系列验证,看用户的输入是否符合要求。
二。网页表单验证实例
<!DOCTYPE html>
<html lang='zh-CN'>
<head>
<title>注册验证</title>
<meta charset='utf-8'>
<script src='myAjax.js'></script>
</head>
<body>
<form action='http://127.0.0.1:3000/reqRes' method='post' onsubmit='return checkForm()'>
用户名:<input type='text' name='username'><span></span><br><br>
密 码:<input type='password' name='pass'><span></span><br><br>
确认密码:<input type='password' name='repass'><span></span><br><br>
邮 箱:<input type='text' name='email' ><span></span><br><br>
手 机:<input type='text' name='phone' ><span></span><br><br>
<input type='submit' value='提交' name=''>
<input type='reset' value='重写' name=''>
</form>
</body>
<script>
//定义标志,所有标志为1才能提交注册
var flag_user = flag_pass = flag_repass = flag_email = flag_phone = 0;
//获取所有input节点
var inputs = document.getElementsByTagName('input');
console.log(inputs);
//获取所有的span标签,用于给出提示信息
var spans = document.getElementsByTagName('span');
//遍历input节点,给不同的input的绑定不同的事件
for(var i = 0; i < inputs.length; i++){
if(inputs[i].name == 'username'){ // 匹配到用户名,进行验证
var index_u = i; //保存i的值,作为下标
//绑定获得焦点事件,获得焦点清空输入框
inputs[index_u].onfocus = function(){
//获取焦点事件提示用户输入正确格式
spans[index_u].innerHTML = '用户名为6-16为英文、数字和下划线组成';
this.value = ''; // 清空输入框
}
//绑定失去焦点事件,失去焦点进行验证
inputs[index_u].onblur = function(){
//失去焦点先进行用户名的格式验证,
//符合要求才发送Ajax到服务器验证是否存在
var reg = /^[a-zA-Z\d_]\w{6,16}$/;//正则表达式
if(reg.test(this.value)){
//验证成功,Ajax远程请求服务器进行用户名验证
Ajax('json',false).post('http://127.0.0.1:3000/checkReg',{username:this.value},function(data){
//判断结果,执行不同的操作
if(data.flag == 0){ //该用户不存在于数据库,可以注册
flag_user = 1;
spans[index_u].innerHTML = data.message;
}else{
flag_user = 0;
spans[index_u].innerHTML = data.message;
}
});
}else{ //验证失败,提示用户
spans[index_u].innerHTML = '用户名格式不正确'; //提示用户
}
}
} else if(inputs[i].name == 'pass'){//密码只进行格式验证
var index_p = i;
var reg_p = /^[a-zA-Z\d]{6,16}$/; //正则匹配
//绑定获得焦点事件,获取焦点清空输入框
inputs[index_p].onfocus = function(){
//获得焦点事件提示用户输入正确格式
spans[index_p].innerHTML = '密码为6-16为英文、数字组成';
//清空输入框的值;
this.value = '';
};
//失去焦点事件,失去焦点
inputs[index_p].onblur = function(){
if(reg_p.test(this.value)){
flag_pass = 1;
spans[index_p].innerHTML = '密码格式正确';
}else{
flag_pass = 0;
spans[index_p].innerHTML = '密码格式不正确';
}
}
} else if(inputs[i].name == 'repass'){
var index_r = i;
//绑定获得焦点事件,获取焦点清空输入框
inputs[index_r].onfocus = function(){
//获得焦点事件提示用户输入正确格式
spans[index_r].innerHTML = '请输入重复密码进行比对';
//清空输入框的值;
this.value = '';
};
//失去焦点事件,失去焦点
inputs[index_r].onblur = function(){
if(inputs[index_p].value == inputs[index_r].value){
flag_repass = 1;
spans[index_r].innerHTML = '重复密码正确';
}else{
flag_repass = 0;
spans[index_r].innerHTML = '密码不一致';
}
}
} else if(inputs[i].name == 'email'){
var index_e = i;
//正则验证邮箱
var reg_e = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
//绑定获得焦点事件,获取焦点清空输入框
inputs[index_e].onfocus = function(){
//获得焦点事件提示用户输入正确格式
spans[index_e].innerHTML = '请输入正确的邮箱格式';
//清空输入框的值;
this.value = '';
};
//失去焦点事件,失去焦点
inputs[index_e].onblur = function(){
if(reg_e.test(this.value)){
flag_email = 1;
spans[index_e].innerHTML = '邮箱格式正确';
}else{
flag_email = 0;
spans[index_e].innerHTML = '邮箱格式不正确';
}
}
} else if(inputs[i].name == 'phone'){
var index_ph = i;
//正则验证
var reg_ph = /^1[3|4|5|8]\d{9}$/;
//绑定获得焦点事件,获取焦点清空输入框
inputs[index_ph].onfocus = function(){
//获得焦点事件提示用户输入正确格式
spans[index_ph].innerHTML = '请输入正确的手机号';
//清空输入框的值;
this.value = '';
};
//失去焦点事件,失去焦点
inputs[index_ph].onblur = function(){
if(reg_ph.test(this.value)){
flag_phone = 1;
spans[index_ph].innerHTML = '手机格式正确';
}else{
flag_phone = 0;
spans[index_ph].innerHTML = '手机格式不正确';
}
}
}
}
//当所有的表单都验证通过了之后才能提交发送
function checkForm(){
if(flag_user == 1 && flag_pass == 1 && flag_repass == 1 && flag_email == 1 && flag_phone == 1 ){
//所有验证都通过返回true,允许表单提交
return true;
}else{
//条件不通过返回false,阻止表单提交
return false;
}
}
</script>
</html>
下面是另外一个表单验证的实例,使用了一丢丢的VUE的知识
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<title>js表单验证</title>
<style type="text/css">
body,
div,
h2,
p,
input,
span,
label {
margin: 0px;
padding: 0px;
}
.head {
width: 800px;
height: 60px;
margin: 50px auto;
border: 1px #ccc solid;
text-align: center;
}
h2 {
line-height: 60px
}
.content {
width: 900px;
margin: 30px auto;
border: 1px solid #ccc;
}
#sub_content {
padding: 10px;
width: 800px;
margin: 1px auto;
}
#sub_content label {
display: inline-block;
width: 100px;
height: 32px;
line-height: 32px;
color: #666;
text-align: right;
}
#sub_content .userName {
width: 200px;
height: 25px;
line-height: 25px;
border: 1px solid #CCC;
}
.choose .default,
#sub_content .default {
width: 200px;
height: 32px;
line-height: 32px;
color: #999;
font-size: 13px;
}
.choose {
padding: 10px;
width: 800px;
margin: 1px auto;
}
.choose label {
display: inline-block;
width: 100px;
height: 32px;
line-height: 32px;
color: #666;
text-align: right;
}
.choose .specil {
display: inline-block;
width: 50px;
height: 32px;
line-height: 32px;
color: #666;
text-align: left
}
#sub_content .error {
height: 32px;
line-height: 32px;
color: #F00;
font-size: 13px;
}
#sub_content .success {
height: 32px;
line-height: 32px;
color: #096;
}
.divBtn {
margin-top: 20px;
margin-left: 200px;
width: 100px;
height: 32px;
line-height: 32px;
background-color: #F93;
margin-bottom: 10px;
color: #ffffff;
font-weight: bold;
border: none;
}
</style>
</head>
<body>
<div>
<div class="head">
<h2>新用户注册</h1>
</div>
<div class="content">
<form action="#" id="myform" method="POST">
<div id="sub_content">
<label for="userName">用户名:</label>
<input type="text" id="userName" name="BasicInformation" class="userName" onBlur="checkUserName()" oninput="checkUserName()" maxlength="20"
required>
<span class="default" id="nameErr">请输入至少3位的用户名</span>
</div>
<div id="sub_content">
<label for="userPasword">密码:</label>
<input type="password" id="userPasword" name="BasicInformation" class="userName" onBlur="checkPassword()" oninput="checkPassword()" maxlength="11"
required>
<span class="default" id="passwordErr">请输入6到11位的密码</span>
</div>
<div id="sub_content">
<label for="userConfirmPasword">确认密码:</label>
<input type="password" id="userConfirmPasword" class="userName" onBlur="ConfirmPassword()" oninput="ConfirmPassword()" required>
<span class="default" id="conPasswordErr">请再输入一遍密码</span>
</div>
<div id="sub_content">
<label for="userEmali">电子邮箱:</label>
<input type="text" id="userEmail" name="BasicInformation" class="userName" onBlur="checkEmail()" oninput="checkEmail()">
<span class="default" id="EmailErr">请输入正确的邮箱号码</span>
</div>
<div class="choose" id="specil">
<label for="userIden">您的身份:</label>
<input type="radio" id="student" class="userName" value="学生" name="identity" v-model="iden">
<label for="student" class="specil">学生</label>
<input type="radio" id="teacher" class="userName" value="老师" name="identity" v-model="iden">
<label for="teacher" class="specil">老师</label>
<input type="radio" id="parent" class="userName" value="家长" name="identity" v-model="iden">
<label for="parent" class="specil">家长</label>
<input type="radio" id="others" class="userName" value="其他" name="identity" v-model="iden">
<label for="others" class="specil">其他</label>
<span class="default">您选择的是: {{iden}}</span>
</div>
<div class="choose" id="specil2">
<label for="userHobby">您的爱好:</label>
<input type="checkbox" id="bb" class="userName" value="篮球" name="hobby" v-model="hobby">
<label for="bb" class="specil">篮球</label>
<input type="checkbox" id="fb" class="userName" value="足球" name="hobby" v-model="hobby">
<label for="fb" class="specil">足球</label>
<input type="checkbox" id="pp" class="userName" value="摄影" name="hobby" v-model="hobby">
<label for="pp" class="specil">摄影</label>
<input type="checkbox" id="others2" class="userName" value="其他" name="hobby" v-model="hobby">
<label for="others2" class="specil">其他</label>
<span class="default">您的爱好有: {{hobby}}</span>
</div>
<div id="sub_content">
<label for="userPhone">手机号码:</label>
<input type="text" id="userPhone" name="BasicInformation" class="userName" onBlur="checkPhone()" oninput="checkPhone()" required maxlength="11">
<span class="default" id="phoneErr">请输入11位手机号码</span>
</div>
<div>
<button type="submit" class="divBtn" id="btn">注册</button>
</div>
</form>
</div>
</div>
<div>
<button id="btn2">show data</button>
<div id="show">
</div>
</div>
<script type="text/javascript">
var iden = new Vue({
el: '#specil',
data: {
iden: "学生",
}
})
var hob = new Vue({
el: '#specil2',
data: {
hobby: []
}
})
var form = document.getElementById('myform');
var oBtn = document.getElementById('btn');
function checkForm() {
var nametip = checkUserName();
var passtip = checkPassword();
var conpasstip = ConfirmPassword();
var phonetip = checkPhone();
var Emailtip = checkEmail();
return nametip && passtip && conpasstip && phonetip && Emailtip;
}
function checkUserName() {
var userName = document.getElementById('userName');
var errorName = document.getElementById('nameErr');
if (userName.value.length == 0) {
errorName.innerHTML = "用户名不能为空!";
errorName.className = "error";
return false;
} else if (userName.value.length < 3) {
errorName.innerHTML = "用户名不合规范";
errorName.className = "error";
return false;
} else {
errorName.innerHTML = "√";
errorName.className = "success";
return true;
}
}
function checkPassword() {
var userPass = document.getElementById('userPasword');
var errorPass = document.getElementById('passwordErr');
var re = /^\w{6,11}$/
if (!re.test(userPass.value)) {
errorPass.innerHTML = "密码不合规范";
errorPass.className = "error";
return false;
} else {
errorPass.innerHTML = "√";
errorPass.className = "success";
return true;
}
}
function ConfirmPassword() {
var userpasswd = document.getElementById('userPasword');
var userConPassword = document.getElementById('userConfirmPasword');
var errConPasswd = document.getElementById('conPasswordErr');
if ((userpasswd.value) != (userConPassword.value) || userConPassword.value.length == 0) {
errConPasswd.innerHTML = "上下密码不一致"
errConPasswd.className = "error";
return false;
} else {
errConPasswd.innerHTML = "√"
errConPasswd.className = "success";
return true;
}
}
function checkEmail() {
var userEmali = document.getElementById('userEmail');
var EmailErr = document.getElementById('EmailErr');
var re = /\w+@[a-z0-9]+\.[a-z]+/i;
if (!re.test(userEmali.value)) {
EmailErr.innerHTML = "邮箱格式错误"
EmailErr.className = "error";
return false;
} else {
EmailErr.innerHTML = "√"
EmailErr.className = "success";
return true;
}
}
function checkPhone() {
var userphone = document.getElementById('userPhone');
var phonrErr = document.getElementById('phoneErr');
var re = /^1[34578]\d{9}$/; //验证手机号正则表达式
if (!re.test(userphone.value)) {
phonrErr.innerHTML = "手机号码不合规范"
phonrErr.className = "error"
return false;
} else {
phonrErr.innerHTML = "√"
phonrErr.className = "success";
return true;
}
}
var show = document.getElementById("show");
var oBtn2 = document.getElementById("btn2");
var elements = new Array();
var iden = new Array();
var hob = new Array();
var BasicInformation = form.elements["BasicInformation"];
var oIden = form.elements["identity"];
var oHob = form.elements["hobby"];
function Xulie()
{
var data = {
用户名: elements[0],
密码: elements[1],
身份: iden,
爱好: hob,
Email: elements[2],
tel: elements[3]
}
str = JSON.stringify(data);
}
oBtn2.onclick = function () {
for (var j = 0; j < BasicInformation.length; j++) {
elements.push(BasicInformation[j].value);
}
for (var j = 0; j < oIden.length; j++) {
if (oIden[j].checked)
iden.push(oIden[j].value);
}
for (var j = 0; j < oHob.length; j++) {
if (oHob[j].checked)
hob.push(oHob[j].value);
}
Xulie();
show.innerHTML = str;
console.log(str)
}
btn.onclick = function () {
if (checkForm() == false) {
form.setAttribute("onsubmit", "return false")
}
if (checkForm() == true)
{
form.setAttribute("onsubmit", "return true");
Xulie();
var xmlhttp;
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
xmlhttp = new XMLHttpRequest();
}
else {
// IE6, IE5 浏览器执行代码
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST", "str.json", true);
//xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send();
}
}
</script>
</body>
</html>