2

I'm having spent several hours trying to find a way to do this but haven't been successful. I want to add a Keyup/KeyPress event to only accept value between 2 - 1827. I'm using aspx inputbox and here's what I have.

$('#Field_TXT').keyup(function () {
            var regex = /[^2-9]|[^1-9][^0-9]|[^1-9][^0-9][^0-9]|[^1][^0-8][^0-2][^0-7]/;
            var myregexp = /^([1-9]|1[0-9]|1[0-9][0-9]|[1-9][0-9][0-9]|1[0-8][0-2][0-7])$/g;


            if (!this.value.match(myregexp)) {
                this.value = this.value.replace(regex, '');
            }
        });

If I use the regex as my expression, then when the user input 1 -19, it doesn't work since the expression matches false and the value is replace with ''. However, if I use the 2nd regexp, then the use will be able to enter 1.

I have also looked at other examples posted. HTML Text Input allow only Numeric input

Thanks in advance.

Community
  • 1
  • 1
Tan Pham
  • 21
  • 3
  • 1
    What's the input to be inserted? A **single** number between 2 and 3000 or exactly a range(eg 7-1000)? And, in this case, are spaces allowed(eg 7 - 1000)? – Niccolò Campolungo Sep 04 '13 at 06:35
  • The input is a number between that range. – Tan Pham Sep 04 '13 at 17:04
  • I can't use html5 since I have users who do not have the option of using the latest browser. – Tan Pham Sep 04 '13 at 17:08
  • 1
    You can easily do `var num = parseInt(this.value); if(num >= 2 && num <= 3000) {...} else {...}` – Niccolò Campolungo Sep 04 '13 at 18:52
  • I could do that, but that doesn't provide me with a way to limit the input while the user is entering the data. for the check, I would use the blur, change, etc. – Tan Pham Sep 04 '13 at 20:22
  • 1
    You could easily use `onkeyup` – Niccolò Campolungo Sep 05 '13 at 06:28
  • FYI, it is possible with regex, though I wouldn't recommend it - for example, the regex for larger than 2 and less than 3000 is: `^([3-9]|\d{2,3}|[1-2]\d{3})$` ... not very pretty! >2 and <1827 is even worse: `^([3-9]|\d{2,3}|1[0-7]\d{2}|18[01]\d|182[0-6])$` – MDEV Sep 10 '13 at 16:14
  • Note that key events are not sufficient validation, because the user may modify the value using the browser's _Edit_ menu or via drag'n'drop. Why don't you go for a simple "any number" validation on the key event and then do the range validation on blur? (And you _are_ validating server-side too, right?) – nnnnnn Oct 23 '13 at 21:05

1 Answers1

0

Regex seems like the hardest way possible to accomplish this. The following ensures that the entry is both numeric and within range. What you do with the field after that is up to you...

$('#Field_TXT').keyup(function() {
    var val = $(this).val();
    var is_numeric = /^\d+$/gi.test(val);
    if (is_numeric) {
        var val = parseInt(val);
        var within_range = (val >= 2 && val <= 1827);
    }
    if  (!is_numeric || !within_range) {
        $(this).val(/* Insert whatever value you want here */);
    }
});
colbydauph
  • 364
  • 1
  • 6