jQuery Textbox Whole Number Validation

2019-09-07 02:42发布

I have the script below, which I use to validate input to validate a textbox for no text, and it also usefully doubles to only allow a number between 0 and 10 with up to 3 decimal places.

$('.sourceValidation').keyup(function () {
    if (!this.value.match(/^(([0-9]|10)(\.\d{1,3})?)?$/)) {
    this.value = this.value.replace(/[^0-9\.]/g, '').substring(0,5);}})

I am not entirely sure of this code, but how do I rework it so that it will validate an input between 0 and 99 (whole numbers only), no text, no decimal points.

4条回答
来,给爷笑一个
2楼-- · 2019-09-07 03:22

The regular expression you need to accept only 0 to 99 without anything else is

/^[0-9]{1,2}$/

This means : Accept digits from '0' to '9', 1 or 2 times.

Note that your code does not contain any jquery, this seems to be pure javascript. <-- Edit : this I take back. My bad.

查看更多
家丑人穷心不美
3楼-- · 2019-09-07 03:24
$('.sourceValidation').keyup(function () {
    if (!this.value.match(/^([0-9]{0,2})$/)) {
        this.value = this.value.replace(/[^0-9]/g, '').substring(0,2);
    }
});

The key part is to change the regex from

/^(([0-9]|10)(\.\d{1,3})?)?$/

to

/^([0-9]{0,2})$/

..which is a regex which will allow 0, 1 or 2 digits. It will however allow leading zeroes eg 01, 09 - or even 00. I don't know if this is acceptable in your situation.

Updated fiddle

The replace function is saying [^0-9]/g - which means - replace anything that is not (^) a digit (0-9) and do it through the whole string (g - global). It is then trimming it to 2 characters max (substring(0,2)).

查看更多
小情绪 Triste *
4楼-- · 2019-09-07 03:25

Please find the working version of jquery below

[http://jsfiddle.net/jQmR3/][1]

This allows users to type numbers only if ($.inArray(charpressed, alpha) > -1) { return false; } You can add what characters you need to allow in the array there

查看更多
smile是对你的礼貌
5楼-- · 2019-09-07 03:31

Try this

^[1-9][0-9]?$|^99$

U Can Teast It Link

查看更多
登录 后发表回答