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

Print Friendly, PDF & Email

Using minlength and maxlength attributes of HTML5, you can manage the number of characters allowed to be entered into the input fields. 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 the min and max length of an input field using jQuery. In the example code below, we will implement validation using jQuery for the input text length. 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=""></script>

Using jQuery only

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

jQuery code

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


The validation message is shown in the <p> tag as below.

<input type="text" id="name"/>
<p id="warning-message></p>

Using jQuery Validation Plugin

From the documentation, we can use the example code to show a warning message when a user types more than the minimum number of characters allowed in an input text.

<!doctype html>
    <meta charset="utf-8">
    <title>Makes "field" required having at most 4 characters.</title>
    <link rel="stylesheet" href="">

<form id="myform">
    <label for="field">Required, maximum length 4: </label>
    <input type="text" class="left" id="field" name="field">
    <input type="submit" value="Validate!">
<script src=""></script>
<script src=""></script>
<script src=""></script>
    // just for the demos, avoids form submit
        debug: true,
        success: "valid"
        rules: {
            field: {
                required: true,
                maxlength: 4

Happy coding!

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.