replace实现正则过滤替换非法字符

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>

转载于:https://www.cnblogs.com/lovelyRabbitBaby/p/6257318.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值