开发者

Allow & prevent certain characters in a regular expression?

开发者 https://www.devze.com 2023-03-30 04:25 出处:网络
I want to allow some characters in one list and prevent other in another list. ALLOW These: [A-Za-z0-9 ,.)(]

I want to allow some characters in one list and prevent other in another list.

ALLOW These:

[A-Za-z0-9 ,.)(]

PREVENT These:

[^~!@#$%^&*_+]

This is failing:

Why does this fail?

(function($) {
    $.fn.extend({
        standardOnly: function() {
            return this.each(function() {
                return $(this).keypress(function(e, text) {

                    var keynum;
                    var keychar;
                    var regEx;
                    var allowedKeyNums = [8, 9, 35, 36, 46]; // Backspace, Tab, End, Home, (Delete & period)

                    if (window.event) // IE
                        keynum = e.keyCode;
                    else if (e.which) // Netscape/Firefox/Opera
                        keynum = e.which;
                    else
                        keynum = e.keyCode开发者_开发百科

                    keychar = String.fromCharCode(keynum);
                    regEx = /[^#$]/ // Undesirable characters

                    // Test for keynum values that collide with undesirable characters
                    if ($.inArray(keynum, allowedKeyNums) > -1)
                        return regEx.test(keychar);

                    regEx = /[A-Za-z0-9 ,.)(][^~!@#$%^&*_+]/
                    return regEx.test(keychar);
                });
            });
        }
    });
})(jQuery);


What your're testing for is a valid character followed by an invalid character. Just look for allowed characters. If it fails, you're done, right?

0

精彩评论

暂无评论...
验证码 换一张
取 消