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: $('.fiel
Solution 1:
How about something like this?
$("input").on("change", function() {
var val = Math.abs(parseInt(this.value, 10) || 1);
this.value = val > 25 ? 24 : val;
});
Solution 2:
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]"
Solution 3:
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)$
Solution 4:
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
Solution 5:
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;
}
}
Post a Comment for "Javascript/Jquery: Validate Input With A Number Range"