-1

I have a input field which is of type number so that it can accept numbers only -I am using regex to restrict user to enter special characters -it is working fine on system,but on small device as in my mobile phone the keypad type is only number,but when i am clicking on - it is taking that which i don't want

What i have done

$('#test').on('keypress', function(event) {

  var regex = new RegExp("^[0-9]+$");
  var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
  if (!regex.test(key)) {
    event.preventDefault();
    return false;
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css">
<input type="number" class="form-control" id="test">

It is showing up like this on mobile

this

-i have tried regex to restrict it but not working on phone

Edit I am almost close, i am trying below code,but it is taking minus - first time when i press not the next time,like if i enter 55 then i press - it is not taking it but when i press - before any number it is taking

(function($) {
  $.fn.inputFilter = function(inputFilter) {
    return this.on("input keydown keyup mousedown mouseup select contextmenu drop", function() {
      if (inputFilter(this.value)) {
        this.oldValue = this.value;
        this.oldSelectionStart = this.selectionStart;
        this.oldSelectionEnd = this.selectionEnd;
      } else if (this.hasOwnProperty("oldValue")) {
        this.value = this.oldValue;
        this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
      }
    });
  };
}(jQuery));




$("#uintTextBox").inputFilter(function(value) {


  return ^\d + [.] ? \d + $.test(value);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="uintTextBox" type="tel">
vivek singh
  • 417
  • 2
  • 12
  • 36

2 Answers2

1

Use this regular expression to not allow - character in the beginning with the <input type="tel">:

/^\d*[.]?\d*$/

Please see working fiddle: https://jsfiddle.net/uhkv65yj/

Rahul Sharma
  • 7,768
  • 2
  • 28
  • 54
0
 /* Function allows only numbers and decimal */
$(document).on('keypress','#test',function(eve) {
    if ((  eve.which != 45 ||eve.which != 46 || $(this).val().indexOf('.') != -1 ) 
         && ( eve.which <  48 || eve.which > 57 ) 
         || ( $(this).val().indexOf('.') == 0) 
       )
       {
            eve.preventDefault();
       }
 })
Deepak A
  • 1,624
  • 1
  • 7
  • 16