Javascript Regex to restrict the text field to only numbers (you must allow non-printable keys)

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.

+6
source share
4 answers

The best way here is to use the input event, which handles all your problems. It is supported in all modern browsers. With jQuery you can do the following. Handles all cases by inserting a value with inverse mouse / keyboard space, etc.

 $('.numeric').on('input', function (event) { this.value = this.value.replace(/[^0-9]/g, ''); }); 

Look here

You can check if the input event is supported by checking if this property has an input if you cannot use onkeyup for older browsers.

 if (inputElement.hasOwnProperty('oninput')) { // bind input } else { // bind onkeyup } 
+19
source

A good solution is described in a previous post :

 jQuery('.numbersOnly').keyup(function () { this.value = this.value.replace(/[^0-9\.]/g,''); }); 
+6
source

Try

CSS

 .error{border:1px solid #F00;} 

SCRIPT

 $('#key').on('keydown',function(e){ var deleteKeyCode = 8; var backspaceKeyCode = 46; if ((e.which>=48 && e.which<=57) || (e.which>=96 && e.which<=105) || // for num pad numeric keys e.which === deleteKeyCode || // for delete key, e.which === backspaceKeyCode) // for backspace // you can add code for left,right arrow keys { $(this).removeClass('error'); return true; } else { $(this).addClass('error'); return false; } }); 

Fiddle: http://jsfiddle.net/PueS2/

+1
source

Instead of checking the keyCode event, why don't you just check the changes inside the actual input and then filter out the non numbers?

This example uses keyup so that it can read what was actually entered, which means the character is displayed briefly and then deleted, but hopefully you get my point. This may even give feedback to the user that the character is not allowed. In any case, I think this is the easiest setup, let me know if you need more help to help you with this.

 function filterNonDigits(evt) { var event = evt || window.event; var val = event.target.value; var filtered = val.replace(/[^0-9]/g, ''); if(filtered !== val) { event.target.value = filtered; event.target.className += " error"; } } 

http://jsfiddle.net/mEvSV/1/

(jquery is used solely for easily binding the keyup function, you will not need this for your actual script)

+1
source

Source: https://habr.com/ru/post/954931/


All Articles