Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript/Jquery: validate input with a number range

I'd like to validate an input field within a preconfigured range of numbers. Only numbers from 1 up to 24 are allowed.

How can I do?


With a custom solution like this:

    $('.field').keypress(function(event) {
        var val = parseInt($(this).val()) + HERE_I_SHOULD_SUM_THE_NEWLY_ADDED_DIGIT;
        if(val < 1 || val > 24) event.preventDefault();
    });

I'm able to retrieve the current input value. How can I add the newly added digit?

like image 284
Mich Dart Avatar asked Jun 20 '12 13:06

Mich Dart


3 Answers

How about something like this?

​$("input").on("change", function() {
    var val = Math.abs(parseInt(this.value, 10) || 1);
    this.value = val > 25 ? 24 : val;
});​​​​​​​​​​​​​

DEMO: http://jsfiddle.net/3jw4S/

like image 167
VisioN Avatar answered Sep 28 '22 16:09

VisioN


There are builtin functionalities for inputs in modern browsers:

A comprehensive overview can be found here: http://www.the-art-of-web.com/html/html5-form-validation/

Basically, you could write:

<input type="number" min="1" max="24" step="1" required>

with pattern you can define regular expressions to test against:

pattern="\d[0-3]"

Example

like image 31
Christoph Avatar answered Sep 28 '22 14:09

Christoph


There's a plugin for JQuery that can help you with validation called Valid8:

http://unwrongest.com/projects/valid8/

You will need to use a regular expression such as this one:

^([1-9]|[1]?[1-9]?|[2][0-4]|10)$
like image 24
Alex W Avatar answered Sep 28 '22 14:09

Alex W