0

Is there a regex or solution that tests an input field for having the following condition (as example)

I would like to test that the user input is only numbers none are decimal, greater than 0 and not greater than 20 for example. Basically I am working on client side scripting for some stuff like Quantity to add in shopping cart and I want to ensure (on client side) that he can put any values from 1 to 20, so 0 not accepted..letters, 1.3 etc...

Is there plugin or regex that tests that for me on client side?

Not sure If i got that right? Here is my attempt

    var re = /^\d+$/;
    var str = $(this).val();
    if (re.test(str) && str > 0 && str <= 20){
        status = 'success';         
    } else {
        status = 'error';
    }
4

2 に答える 2

1

This will work:

/^([1-9]|[1][0-9]|[2][0])$/

It will match 1-20.

Code example

$(function() {
    "use strict";
    var limit = /^([1-9]|[1][0-9]|[2][0])$/,
        value = "19";

    if(limit.test(value)) {
        // Will in this example go here.
    }
    else {
        // Do something when it fails.
    }
});
于 2012-08-24T11:54:30.330 に答える
0

Try this regex on client side,

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

Matches a whole number between 1 and 20 inclusively

于 2012-08-24T11:55:28.963 に答える