Home JQuery检查输入内容是否包含特殊字符
Post
Cancel

JQuery检查输入内容是否包含特殊字符

调用函数判断

1
2
3
4
5
6
7
8
function checkNameReg(val) { 
    var regEn = /[@#$%^&*()[\]]/im,
        regCn = /[@#¥%……&*[\]]/im;
    if(regEn.test(val) || regCn.test(val)) {
        return false;
    }
    return true; 
}

或直接在键入的时候将特殊符号替换

1
2
3
4
5
6
7
$(function() {
    $("#TEST").keyup(function() {  
        var inputNumber = $(this).val();
        inputNumber = inputNumber.replace(/[@#\$%\^&\*\…\¥]/g, '');
        $(this).val(inputNumber);
    });
});

IE使用特殊字符替换时光标跳到最后的解决方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
$(function () {
    $("#TEST").keyup(function () {
        var text = $(this).val();
        var nowPosition = $(this).getCursorPosition();
        var textLength = text.length;
        text = text.replace(/[@#\$\^&\*\…\¥]/g, '');
        if (text.length - textLength < 0) {
            nowPosition = nowPosition - 1;
        }
        $(this).val(text);
        var txtFocus = document.getElementById("TEST");
        var isIE = false || !!document.documentMode;
        if (isIE) {
            var range = txtFocus.createTextRange();
            range.move("character", nowPosition);
            range.select();
        } else {
            txtFocus.setSelectionRange(nowPosition, nowPosition);
            txtFocus.focus();
        }
    });
});

(function ($, undefined) {
    $.fn.getCursorPosition = function () {
        var el = $(this).get(0);
        var pos = 0;
        if ('selectionStart' in el) {
            pos = el.selectionStart;
        } else if ('selection' in document) {
            el.focus();
            var Sel = document.selection.createRange();
            var SelLength = document.selection.createRange().text.length;
            Sel.moveStart('character', -el.value.length);
            pos = Sel.text.length - SelLength;
        }
        return pos;
    }
})(jQuery);
This post is licensed under CC BY 4.0 by the author.