简体   繁体   中英

Javascript functions are not working in Firefox new version

I have the following below function which disables to enter numbers or special characters in the text box. This function are working fine in IE and Chrome, but in the firefox these are not working and am able to enter the numbers and characters. Can anyone please suggest how this can be resolved in firefox? My FF version is 57.0.4

$("#firstName").keypress(function(event) {
        var character = String.fromCharCode(event.keyCode);
        return isValid(character);     
    });


        function isValid(str) {
            return !/[~`!@#$%\^&*()+=\-\[\]\\';,/{}|\\":<>\?]/g.test(str);
        }

         $( document ).ready(function() {
             $( "#firstName" ).keypress(function(e) {
                 var key = e.keyCode;
                 if (key >= 48 && key <= 57) {
                     e.preventDefault();
                 }
             });

keyCode is deprecated. jQuery normalizes this property for cross browser usage in the event.which property.

 $("#firstName").keypress(function(event) { var character = String.fromCharCode(event.which); return isValid(character); }); function isValid(str) { return !/[~`!@#$%\\^&*()+=\\-\\[\\]\\\\';,/{}|\\\\":<>\\?]/g.test(str); } $("#firstName").keypress(function(e) { var key = e.which; if (key >= 48 && key <= 57) { e.preventDefault(); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id=firstName /> 

To disables to enter numbers or special characters you can use

/[~`!#@$%\^&*+=\-\[\]\\';,_./{}\(\)\|\\":<>\d+$?]/g 

You can try this regex Here And instead of using keypress() you can use .on('input') .. The next code works for me in chrome , firefox and IE

 $("#firstName").on( 'input' ,function(event) { var ThisVal = $(this).val(); if(isValid(ThisVal) == false){ $(this).val(ThisVal.substr(0, ThisVal.length - 1)); } }); function isValid(str) { return !/[~`!#@$%\\^&*+=\\-\\[\\]\\\\';,_./{}\\(\\)\\|\\\\":<>\\d+$?]/g.test(str); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id=firstName /> 

Note : I don't care here to use e.which or e.keyCode because no need to in this case .. Also this regex will disable _ and . and - if you need any of those you can remove it

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