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?
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/
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
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)$
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With