0

I'm trying to make a function that only allows numbers with any amount of digits and not starting with 0, but this validation doesn't works properly, because when I want to paste and drop on the input, it fails for the first time but the next time, works!

jQuery(document).on('input', '.validatenumber', function () {
  let start = this.selectionStart, end = this.selectionEnd;
  let oldtxt = $(this);
  let find = /[^0-9]/g;
  if (oldtxt.val().match(find)) {
    oldtxt.val(oldtxt.val().replace(find, ''));
    this.setSelectionRange(start - 1, end - 1);
  }
  else {
    if (oldtxt.val() < 1) {
      oldtxt.val(oldtxt.val().replace(oldtxt.val(), ''));
    } else {
     oldtxt.val(oldtxt.val() / 1);
      this.setSelectionRange(start, end);
   }
  }
});

why only when I typing works but not when I paste or drop?

Lrawls
  • 193
  • 1
  • 3
  • 16

1 Answers1

2

You can use this RegEx

^[1-9][0-9]*$

For explanation check this image

enter image description here

Hemant Pawar
  • 360
  • 1
  • 3
  • 14
  • 2
    If negatives or decimals are desired, this can be modified to `^((-?([1-9][0-9]*(\.[0-9]*[1-9])?|0\.[0-9]*[1-9])|0))$` which won't allow trailing `0`'s in decimals, won't allow `-0`, or preceding `0`'s (either before or after `-`) – Patrick Barr Jul 26 '17 at 15:37