How to Validate Min and Max Length of Input Field using jQuery

Using minlength and maxlength attributes of HTML5, you can manage input field text length. But if you want to show a custom validation message, it can be done easily with jQuery. In this tutorial, we will show you how to validate min and max length of input field using jQuery.

In the example code, we will implement input text length validation using jQuery. Based on the user input the validation message will be shown beside the input field.

Include the jQuery library to validate input field length using jQuery.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

jQuery
Based on the minimum (minLength) and maximum (maxLength) value the input length is validated. If the length exceeds, the additional value will be removed.

var minLength = 5;
var maxLength = 10;
$(document).ready(function(){
    $('#card').on('keydown keyup change', function(){
        var char = $(this).val();
        var charLength = $(this).val().length;
        if(charLength < minLength){
            $('span').text('Length is short, minimum '+minLength+' required.');
        }else if(charLength > maxLength){
            $('span').text('Length is not valid, maximum '+maxLength+' allowed.');
            $(this).val(char.substring(0, maxLength));
        }else{
            $('span').text('Length is valid');
        }
    });
});

HTML
The validation message is shown in the <span> tag.

<input type="text" id="card"/>
<span></span>

3 Comments

  1. Jack Sparrow Said...
  2. Shyam Said...
  3. Addy Brown Said...

Leave a reply

keyboard_double_arrow_up