禁止所有文本框输入特殊字符

 1 function getValue(o) {
 2     if (o.tagName != '') {
 3         tagname = o.tagName;
 4     }
 5     if ($(o).attr('id')) {
 6         attrid = $(o).attr('id');
 7     }
 8     if ($(o).val()) {
 9         tagvalue = $(o).val();
10     }
11 }
12 var tagname = '';
13 var attrid = '';
14 var tagvalue = '';
15 document.oninput = function (e) {
16     var o = e.srcElement || e.target;
17     getValue(o);
18     if (tagname != '' && (tagname == 'INPUT' || tagname == 'TEXTAREA')) {
19         if (tagvalue != '' && !/^[^\;'&"<>]*$/.test(tagvalue)) {
20             var str = tagvalue.replace(/;/gm, '').replace(/\\/gm, '').replace(/&/gm, '').replace(/"/gm, '').replace(/</gm, '').replace(/>/gm, '');
21             $(o).val(str);//把过滤特殊字符后的内容赋值给文本框
22             tagvalue = '';//当输入第一个字符为特殊字符,回退键删除后会有缓存
23             return false;
24         }
25         return true;
26     }
27 };
28 document.onkeydown = function (e) {
29     var o = e.srcElement || e.target;
30     getValue(o);
31     //console.log(e.keyCode);
32     if (tagname != '' && (tagname == 'INPUT' || tagname == 'TEXTAREA')) {
33         if (e.keyCode == 222 || e.keyCode == 220 || (e.keyCode == 220 && e.shiftKey)) {
34             return false
35         }
36     }
37     return true;
38 };

 

posted @ 2017-09-04 11:25  老-顾  阅读(1123)  评论(0编辑  收藏  举报