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.


Libraries

First of all include jQuery latest library on page.

<script src="//code.jquery.com/jquery-latest.min.js"></script>

HTML

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" />
<span></span>



JS

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.");
    else
        $("span").text("Text is valid");
  });
});

See live demo and download source code.

DEMO | DOWNLOAD


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.