Simple jQuery Snippet to Validate Min and Max Length of Input Field with Custom Message

Using default HTML5 minlength and maxlength attributes you can simply manage input field text length. But if you want to display a custom validation message, it can be done easily with jQuery. In this tutorial, we will see you how to validate min and max length of input field using jQuery and based on the user input the validation custom message will be display to user so that you can apply more userfriedly validation on form.


First of all include jQuery latest library on page.

<script src="//"></script>


Here is the sample demo input text field where need to implement Min and Max Length validation with custom validation message.

<input type="text" class="demo" />


add bellow jquery lines on page to apply min and max length validation on keydown, keyup, change event. also define your min and max length if length lower form min length or exceed form max lenth you can display custom error message to user.

$(function() {   
  var minLength = 5;
  var maxLength = 15;
  $(".demo").on("keydown keyup change", function(){
    var value = $(this).val();
    if (value.length < minLength)
        $("span").text("Text is short, minimum "+minLength+" character required.");
    else if (value.length > maxLength)
        $("span").text("Text is long, maximum "+maxLength+" character allowed.");
        $("span").text("Text is valid");

See live demo and download source code.