I am using the Jquery Validation plug-in and I couldn't get it working correctly. What I like to validate is only allowing using enter range from 0 to 100 in the field, not allow 0.1, .5, -11.4. Currently, if I enter 0.5, it recognizes a valid number even though I set the range: [0, 100].
Fiddle Link: https://jsfiddle.net/milacay/e4fe4hsz/3/
I have two questions:
Thanks in advance,
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Makes "field" required and between 0 and 100.</title>
<link rel="stylesheet" href="https://jqueryvalidation.org/files/demo/site-demos.css">
</head>
<body>
<form id="myform">
<label for="field">Required, minium 0, maximum 100:</label>
<input type="text" class="left" id="field" name="field">
<br/>
<input type="submit" value="Validate!">
</form>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/additional-methods.min.js"></script>
<script>
// just for the demos, avoids form submit
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$( "#myform" ).validate({
rules: {
field: {
required: true,
range: [0, 100]
}
}
});
</script>
</body>
</html>
Currently, if I enter
0.5
, it recognizes a valid number even though I set the range:[0, 100]
.
That's because the range
rule accepts decimal numbers. Since 0.5
is greater than zero, it's valid.
How can I only allow whole number from 0 to 100 (Not 44.3, but 44.0 is OK)?
Just add the integer
rule (part of the additional-methods.js file).
$( "#myform" ).validate({
rules: {
field: {
required: true,
integer: true, // <- here
range: [0, 100]
}
}
});
The default digits
rule should work just as well in this case, since you don't have any negative numbers. IMO, since you just want to exclude decimal numbers, stick with integer
so if your range
ever needs to go negative, you will not break it.
DEMO: jsfiddle.net/e4fe4hsz/5/
How can I allow decimal number says from 0.5 to 50?
You are already doing this; it's what you're complaining about in question #1.
(Obviously, you cannot simultaneously allow and disallow decimal numbers, so not sure what this part of the question is really all about.)
$( "#myform" ).validate({
rules: {
field: {
required: true,
range: [0.5, 50] // <- here
}
}
});
DEMO: jsfiddle.net/e4fe4hsz/7/
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments