使用
<input type="text" οninput="inputCheck.tel(this)" />
/*输入框拼写检查*/
//分两个方向 一个是限制输入 一个是提示错误 这里是限制输入var inputCheck={
//限制只能输入正确的数据
Number:function(obj){
//先把非数字的都替换掉,除了数字和.
obj.value = obj.value.replace(/[^\d\.]/g,'');
//必须保证第一个为数字而不是.
obj.value = obj.value.replace(/^\./g,'');
//保证只有出现一个.而没有多个.
obj.value = obj.value.replace(/\.{2,}/g,'.');
//保证.只出现一次,而不能出现两次以上
obj.value = obj.value.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
},
//限制只能输入纯整数
Integer:function(obj){
//先把非数字的都替换掉,除了数字
obj.value = obj.value.replace(/[^\d]/g,'');
//保证第一位不是0
obj.value = obj.value.replace(/^[0]/g,'');
},
//限制输入最多为11位以1开头的数字
tel:function(obj){
//先把非数字的都替换掉,除了数字
obj.value = obj.value.replace(/[^\d]/g,'');
//保证第一位是1
obj.value = obj.value.replace(/^[02-9]/g,'');
//保证长度不大于11 手机号
if(this.getLength(obj.value) > 11){
obj.value = obj.value.substring(0,11);
}
},
getLength:function(str){
///<summary>获得字符串实际长度,中文2,英文1</summary>
///<param name="str">要获得长度的字符串</param>
var realLength = 0, len = str.length, charCode = -1;
for (var i = 0; i < len; i++) {
charCode = str.charCodeAt(i);
if (charCode >= 0 && charCode <= 128) realLength += 1;
else realLength += 2;
}
return realLength;
}
};