简体   繁体   中英

Allow & prevent certain characters in a regular expression?

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM