I received the PHP / JS code from a previous developer, and I need to add a quantity check in the Mobile Number field. I already have the HTML check in place, but I need to add that if someone presses an invalid key, it is not displayed only to highlight the field later in red, because it contains invalid input.
I saw a lot of regular expressions that were used and tried them, but they had either / or the effect of what I need: if a letter or special character is entered, do not accept and do not show all other input data (numbers, keys) (me we need an invalid character that is not displayed at all, is not displayed, and then deleted). The basic rule that works the most is the following:
function filterNonDigits(evt) { var event = evt || window.event; var keyentered = event.keyCode || event.which; keyentered = String.fromCharCode(keyentered); //var regex1 = /[0-9]|\./; var regex2 = /^[a-zA-Z.,;:|\\\/ ~!@ #$%^&*_-{}\[\]()`"'<>?\s]+$/; if( regex2.test(keyentered) ) { event.returnValue = false; if(event.preventDefault) event.preventDefault(); }
When I used the programmed regex1 (with the modified IF condition), of course, it limited the input to numbers, thereby preventing all keys, such as Delete, BackSpace, etc. When using regex2, I still cannot press Delete or numbers from the numeric keypad.
So my question is: can this code be modified to accept only numbers, but also allow keys? Another important point is that I need a method that does not use key codes (8, 24, etc.) for this key to make sure that all types of keyboards can be used.
New update:
So my solution is this: if the βoninputβ property exists, I will use the solution provided by Ehtesham, and if it is not, the backup will use the solution provided by Rohan Kumar. So something like this:
if (obj.hasOwnProperty('oninput') || ('oninput' in obj)) { $('#mobileno').on('input', function (event) { this.value = this.value.replace(/[^0-9]/g, ''); }); } else { $('#mobileno').on('keypress',function(e){ var deleteCode = 8; var backspaceCode = 46; var key = e.which; if ((key>=48 && key<=57) || key === deleteCode || key === backspaceCode || (key>=37 && key<=40) || key===0) { character = String.fromCharCode(key); if( character != '.' && character != '%' && character != '&' && character != '(' && character != '\'' ) { return true; } else { return false; } } else { return false; } }); }
Thanks.