form表单验证封装
程序员文章站
2022-04-25 15:47:16
...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="index.css">
<script src="../../jquery-3.3.1.js"></script>
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aaa@qq.com/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
<script src="https://cdn.jsdelivr.net/npm/aaa@qq.com/dist/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="./index.js"></script>
<style>
.tip-error{
display:none;
background-color:bisque;
}
</style>
</head>
<body>
<form class="form-horizontal" style="width: 600px;margin: 40px auto;">
<div class="form-group">
<label class="col-sm-2 control-label">Email</label>
<input type="text" class="col-sm-6 form-control1" placeholder="email">
<span class="tip-error col-sm-4">输入有误</span>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">手机号</label>
<input type="text" class="col-sm-6 form-control2" placeholder="手机号">
<span class="tip-error col-sm-4">输入有误</span>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">姓名</label>
<input type="text" class="col-sm-6 form-control3" placeholder="姓名">
<span class="tip-error col-sm-4">输入有误</span>
</div>
</form>
</body>
</html>
js:
//next紧邻的下一个元素
//siblings('.class') 同级的兄弟元素 不传参数表示所有的同级
//正则表达式 ^开始 $结束 /^[\u4eoo-\u9fa5]{2,4}$/.test(str) 正则匹配
$(function(){
$(".form-group input").on('focus',function(){
$(this).siblings('.tip-error').hide();
});
//邮箱
$(".form-group .form-control1").on('blur',function(){
var value=$(this).val();
var filte=/[a-zA-Z0-9]{1,10}@[a-zA-Z0-9]{1,5}\.[a-zA-Z0-9]{1,5}/;
formEvent(value,$(this),filte,'邮箱不能为空','邮箱格式不正确')
})
//用户名var reg=/^[\u4e00-\u9fa5]{2,4}$/; 2-4个汉字
$(".form-group .form-control3").on('blur',function(){
var value=$(this).val();
var filte=/^[\u4e00-\u9fa5]{2,4}$/;
formEvent(value,$(this),filte,'用户名不能为空','用户名为2-4个汉字')
})
//手机号var reg=/^1[0-9]{10}/;
$(".form-group .form-control2").on('blur',function(){
var value=$(this).val();
var filte=/^1[0-9]{10}/;
formEvent(value,$(this),filte,'手机号不能为空','请输入正确的手机号')
})
function formEvent(value,cur,filte,str1,str2){
if(value==""){
cur.siblings('.tip-error').show().text(str1);
}else if (!filte.test(value)) {
cur.siblings('.tip-error').show().text(str2);
}else{
cur.siblings('.tip-error').hide();
}
}
})