7

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;
}
});
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. Commented May 5, 2016 at 18:20

2 Answers 2

9

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

<input type="text" minlength="8" maxlength="14" name="354" id="field">

Sign up to request clarification or add additional context in comments.

1 Comment

How can I achieve this using jquery?
7

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.