Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery min and maxlength validation

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;
}
});
like image 830
Jason Avatar asked May 05 '16 18:05

Jason


2 Answers

Now with HTML5 you can use the properties minlength and maxlength.

<input type="text" minlength="8" maxlength="14" name="354" id="field">
like image 142
Wowsk Avatar answered Oct 20 '22 01:10

Wowsk


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>
like image 23
Mohammad Avatar answered Oct 20 '22 00:10

Mohammad