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?
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?
Share Improve this question edited Jul 12, 2012 at 11:29 Kev 120k53 gold badges305 silver badges391 bronze badges asked Jun 20, 2012 at 13:56 Mich DartMich Dart 2,4225 gold badges27 silver badges47 bronze badges5 Answers
Reset to default 11How 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)$
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x <1|| x >24)
{
alert("Value must be between 1 & 24");
return false;
}
}
Something along those lines should work
Try this
function validate() {
var x = parseInt(value,10) // its the value from the input box;
if(isNaN(x)||x<1||x>24)
{
alert("Value must be between 1 and 24");
return false;
}
}