html+js結構如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery i18n Plugin</title>
<style>
div{
width: 400px;
margin: 100px auto;
}
input{
width: 300px;
height: 32px;
margin-top: 10px;
padding: 0px 10px;
box-sizing: border-box;
}
</style>
<script type="text/javascript" src="js/jquery.js"></script>
<body>
<div>
<input type="text" placeholder="請輸入中文數字字母下划線" data-type="name"/>
<input type="text" placeholder="請輸入數字字母下划線" data-type="mix"/>
<input type="text" placeholder="請輸入手機號" data-type="telephone"/>
<input type="text" placeholder="請輸入郵箱" data-type="email"/>
</div>
<script type="text/javascript">
$(document).ready(function(){
var html = '';//用來存放input校驗后的value
//獲得焦點事件
$('body').on('focus','input',function(){
html = $(this).val();
})
//輸入框修改事件
$('body').on('input','input',function() {
var text = '',
inputType = $(this).data("type");
if(inputType=="name"){
regFun($(this),$(this).val(),/^(?!_)[a-zA-Z_0-9\u4e00-\u9fa5]+$/g,"請輸入中文數字字母下划線,不能以下划線開頭")
}else if(inputType=="mix"){
regFun($(this),$(this).val(),/^(?!_)[a-zA-Z_0-9]+$/g,"請輸入數字字母下划線,不能以下划線開頭")
}
});
//用來按下鍵盤直接修改input的value值的情況調用此方法
function regFun(obj,text,regexp,warn){
if(regexp.test(text)){
text.replace(regexp,function(res){
html = res;//如果正則匹配成功將匹配結果賦值給html
});
}else{
if(text!=''){
alert(warn)
}else{
html = '';
}
if(obj.data("type")=="name"){
obj.val(html);
}
}
// return html;
if(obj.data("type")!="name"){
obj.val(html);
}
}
//對於一些像郵箱手機號這樣的用戶輸入完全之后才能校驗的用失去焦點的事件
$('body').on('blur','input',function(){
var inputType = $(this).data("type");
if(inputType=="telephone"){
blurFun($(this),/^1[34578]\d{9}$/,"手機號輸入有誤!")
}else if(inputType=="email"){
blurFun($(this),/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/,"郵箱輸入有誤!")
}
});
//失去焦點事件校驗的方法
function blurFun(obj,regexp,warn){
var text = obj.val();
if(!regexp.test(text)&&text!=''){
console.log(warn);
obj.focus();
}
}
});
</script>
</body>
</html>