If you could help me, I'm using jquery validate and I want to do the following validation:
in an input I just want to accept 0 or a line between 20 and 100
If you could help me, I'm using jquery validate and I want to do the following validation:
in an input I just want to accept 0 or a line between 20 and 100
You should add a custom validation method, you can do it like this:
$.validator.addMethod(
"ranges",
function(value, element, ranges) {
var valid = false;
for(var i = 0; i < ranges.length; i++) {
if (Array.isArray(ranges[i])){
if (ranges[i][0] <= value && value <= ranges[i][1]) {
valid = true;
break;
}
}
else if (value == ranges[i]) {
valid = true;
break;
}
}
return this.optional(element) || valid;
},
"El valor no se encuentra dentro del rango permitido"
);
$( "#form" ).validate({
rules: {
rango: {
required: true,
ranges: [0, [20, 100]]
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.validate.min.js"></script>
<form id="form">
<p>
<label for="rango">Rango (0, 20 - 100)</label>
<input id="rango" name="rango" type="text">
</p>
<p>
<input class="submit" type="submit" value="Submit">
</p>
</form>