###常用表单正则验证
html代码块,例如:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="index.js"></script>/*下面提供index.js*/
<style>
/*样式可自己添加*/
</style>
<body>
<div class="list">
<ul>
<li>
<label>姓名:</label>
<input type="text" name="name" class="name" placeholder="请输入您的姓名">
<span class="tip-error">5235</span>
</li>
<li>
<label>手机:</label>
<input type="text" name="mobile" class="mobile" placeholder="请输入您的手机">
<span class="tip-error"></span>
</li>
<li>
<label>电子邮箱:</label>
<input type="text" name="email" class="email" placeholder="请输入您的电子邮箱">
<span class="tip-error"></span>
</li>
<li>
<label>年龄:</label>
<input type="text" name="age" class="age" placeholder="请输入您的年龄">
<span class="tip-error"></span>
</li>
<li>
<label>通讯地址:</label>
<input type="text" name="address" class="address" placeholder="请输入您的通讯地址">
<span class="tip-error"></span>
</li>
<li class="fn-textcenter"><a href="javascript:;" class="btn-blue btn-submit">提交</a></li>
</ul>
</div>
</body>
</html>
###js部分代码块(index.js)
index.js代码块,例如:
$(function(){
//成为焦点
$('.name,.mobile,.email,.age,.address').on('focus',function(){
$(this).siblings(".tip-error").hide();
})
//失去焦点
$('.name').on('blur',function(e){//下面进行封装
var current = $(e.target);
var value = current.val();
fromEvent(current,value,'name','用户名不能为空!','用户名只能是汉字并且在2-4位之间!');
})
$('.mobile').on('blur',function(e){//下面进行封装
var current = $(e.target);
var value = current.val();
fromEvent(current,value,'mobile','手机号不能为空!','请输入正确的手机号码!');
})
$('.email').on('blur',function(e){
var current = $(e.target);
var value = current.val();
fromEvent(current,value,'email','邮箱不能为空!','请输入正确的邮箱!');
})
$('.age').on('blur',function(e){
var current = $(e.target);
var value = current.val();
fromEvent(current,value,'age','年龄不能为空!','请输入有效数字!');
})
function fromEvent(current,value,name,text1,text2){
if(value == ""){
current.siblings('.tip-error').text(text1).show();
}else if(!checkFilter(name,value)){
current.siblings('.tip-error').text(text2).show();
}else{
current.siblings(".tip-error").hide();
}
}
function checkFilter(name,value){
if(name == '') return true;
var filter;
switch(name){
case 'name':
filter = /^[\u4E00-\u9FA5]{2,4}$/;
break;
case 'mobile':
filter = /^1[34578]\d{9}$/;
break;
case 'email':
filter = /^[0-9|A-z|_]{1,17}[@][0-9|A-z]{1,3}.(com)$/;
break;
case 'age':
filter = /^[0-9]{1,2}$/;
break;
}
if(filter.test(value)){
return true;
}else{
return false;
}
}
})
谢谢大家