I want minlength=8
and maxlength=14
, how can I achieve this validation.
html:
<input type="text" name="354" id="field">
jQuery:
$("input[name=354]").keypress(function(e){
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
$("#errmsg").html("Digits only").show().fadeOut("slow");
return false;
}
});
I want minlength=8
and maxlength=14
, how can I achieve this validation.
html:
<input type="text" name="354" id="field">
jQuery:
$("input[name=354]").keypress(function(e){
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
$("#errmsg").html("Digits only").show().fadeOut("slow");
return false;
}
});
Share
Improve this question
edited May 5, 2016 at 18:36
Hongbin Wang
1,1862 gold badges14 silver badges34 bronze badges
asked May 5, 2016 at 18:15
JasonJason
4151 gold badge7 silver badges17 bronze badges
1
- What do your min and maxlength refer to? All you have here is a keypress event which will fire on each individual key press. If you are trying to validate the field overall, making sure there are 8-14 'digits' in the field then you'll need to validate on submission. – nurdyguy Commented May 5, 2016 at 18:20
2 Answers
Reset to default 9Now with HTML5 you can use the properties minlength
and maxlength
.
<input type="text" minlength="8" maxlength="14" name="354" id="field">
You can use HTML5 attributes minlength
and maxlength
to manage input text length. But if you want to use JQuery to do this work, see this example
var minLength = 3;
var maxLength = 10;
$("input").on("keydown keyup change", function(){
var value = $(this).val();
if (value.length < minLength)
$("span").text("Text is short");
else if (value.length > maxLength)
$("span").text("Text is long");
else
$("span").text("Text is valid");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
<span></span>