658

It seems the minlength attribute for an <input> field doesn't work.

Is there any other attribute in HTML with the help of which I can set the minimal length of a value for fields?

TylerH
  • 20,799
  • 66
  • 75
  • 101
emilan
  • 12,825
  • 11
  • 32
  • 37
  • 3
    It won't be the answer for every field, but if you just want to make sure a value is there you can use the "required" attribute. – None Aug 30 '12 at 22:55
  • 1
    Possible Duplicate: http://stackoverflow.com/questions/5533053/textarea-character-limit/5607015#comment21177768_5607015 – Web_Designer Feb 25 '13 at 21:03
  • 7
    It doesn't exist, but let's make a fuss and get it in! https://www.w3.org/Bugs/Public/show_bug.cgi?id=20557 – Eric Elliott Sep 23 '13 at 04:01
  • You need to use JS/Jquery if you want to do a full implementation (eg. required, minlength, error message when submitting etc). Safari still does not fully support even the required attribute, and only Chrome and Opera support minLength. eg see http://caniuse.com/#search=required – rmcsharry Oct 13 '16 at 12:22

21 Answers21

1408

You can use the pattern attribute. The required attribute is also needed, otherwise an input field with an empty value will be excluded from constraint validation.

<input pattern=".{3,}"   required title="3 characters minimum">
<input pattern=".{5,10}" required title="5 to 10 characters">

If you want to create the option to use the pattern for "empty, or minimum length", you could do the following:

<input pattern=".{0}|.{5,10}" required title="Either 0 OR (5 to 10 chars)">
<input pattern=".{0}|.{8,}"   required title="Either 0 OR (8 chars minimum)">
Martijn
  • 15,791
  • 4
  • 36
  • 68
user123444555621
  • 148,182
  • 27
  • 114
  • 126
  • 146
    +1 for using html5 instead of jQuery. I just wanted to add that the title attribute allows you to set the message to display to the user if the pattern is not met. Otherwise a default message will be shown. – None Aug 30 '12 at 22:46
  • 12
    @J.Money It still says "Please match the requested format: ". Is there a way to bypass the prior default message? – CᴴᴀZ Oct 01 '13 at 07:52
  • 62
    Unfortunately this is **not supported for textareas**. – ThiefMaster Nov 15 '13 at 23:35
  • 5
    Totally works, but the error you get when not meeting the pattern requirements is: "Please match the requested format" or something along those lines. It begs the follow up question: how do you customize the error message :-) – Randy Greencorn Dec 15 '13 at 07:41
  • @RandyGreencorn It's the browser's choice whether or not they use the `title` attribute as the error message: *User agents **may** use the contents of this attribute, if it is present, when informing the user that the pattern is not matched…* http://www.w3.org/TR/2009/WD-html5-20090825/forms.html#attr-input-pattern – user123444555621 Dec 15 '13 at 17:47
  • 1
    I am testing with Chromium and when I insert 2 characters, it correctly tells me "please match the requested format", but when I insert 0 characters it doesn't complain and submits the form :-( – knocte Dec 26 '13 at 11:43
  • 1
    Would eg `` be a better example, as avoids waiting until submit to satisfy max length condition? – neil Feb 21 '14 at 11:25
  • is there a way for setting a custom error message is the validation is not ok ? – Basj Oct 07 '14 at 20:47
  • 28
    @ChaZ @Basj You can add a custom error message by adding the following attribute: `oninvalid="this.setCustomValidity('Your message')"` – bigtex777 Nov 26 '14 at 20:31
  • 1
    on a related note, this is a great website to test your Regular expressions before including them on your HTML5 forms - [RegExr](http://www.regexr.com/) – Ashesh Mar 08 '15 at 18:48
  • on firefox and chrome add a title attribute to the field in order to append some information to the standard error message. For example `title="8 characters minimum"` will display "Please match the requested format: 8 characters minimum". Saves on inline javascript. – Phil Aug 07 '15 at 14:37
  • It is noteworthy that: since the pattern attributes executes the regular expression; you should use ^ and $ as necessary. E.G ` pattern="^[0-9]{2}$" ` permits EXACTLY two integers in the input field. – tormuto Sep 02 '15 at 09:56
  • @knocte make sure the input type is 'text' and the required attribute is set. The pattern attribute will not be effective for some standard input type e.g type='number' or type='url' – tormuto Sep 02 '15 at 10:03
  • 10
    If you enters an invalid input and you're using `setCustomValidity`, then it will continue to show you the error message even after you corrected the input. You can use the following `onchange` method to counter this. **`oninvalid="this.setCustomValidity('Field must contain min. 5 characters')" onchange="try{setCustomValidity('')}catch(e){}"`** – sohaiby Oct 24 '15 at 08:56
  • 1
    Is there any way to implement this in Safari because Safari doesn't support these attributes? Seems like Js and jQuery are only the solutions for safari. – Koushik Das May 07 '16 at 05:05
  • Required attribute not working on ios devices. And the pattern attributes does not work without the attribute required. This doesnt work on ios devices. – Kiko Aug 24 '16 at 02:33
  • 2
    It doesn't works if the input type is number. Any solution for this? – Krishnadas PC Oct 22 '16 at 12:42
  • 3
    If you are using a pattern for "empty, or minimum length", then you need to remove 'required' (at least for Chrome). – Damien Justin Šutevski Oct 30 '16 at 23:00
  • Do you need to specify `required` for "empty or minimum length"? "The required attribute is also needed, otherwise an input field with an empty value will be excluded from constraint validation." would seem to indicate that you don't. – Arlen Beiler Mar 01 '17 at 18:40
  • Ive been searching for a solution for this: **pattern=".{5,}[0-9]"** where I want minimum 5 characters & can only be 0-9, no spaces, no "**+**" symbols. But **.{5,}[0-9]** allows letters in the middle for some reason. Example: **123kh678**. Any ideas? – Dayley Sep 21 '18 at 13:41
  • For some reason https://regex101.com/ fails to properly parse `.{0}|.{5,10}` solution, always getting group 1 (empty string). If global flag is added, multiple matches are found inbetween characters. – Tomas Dec 11 '18 at 09:01
172

There is a minlength property in the HTML5 specification now, as well as the validity.tooShort interface.

Both are now enabled in recent versions of all modern browsers. For details, see https://caniuse.com/#search=minlength.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
rhgb
  • 4,075
  • 2
  • 21
  • 28
  • 2
    I see this, but still it is not working for me. I have required set as well, but still not validating against the minlength. not sure why. – ggedde Jun 23 '22 at 19:48
24

Here is HTML5-only solution (if you want minlength 5, maxlength 10 character validation)

http://jsfiddle.net/xhqsB/102/

    <form>
      <input pattern=".{5,10}">
      <input type="submit" value="Check"></input>
    </form>
Sᴀᴍ Onᴇᴌᴀ
  • 8,218
  • 8
  • 36
  • 58
Ali Çarıkçıoğlu
  • 1,304
  • 1
  • 12
  • 21
  • 3
    How to set a custom error message if the field is not Ok? – Basj Oct 07 '14 at 20:47
  • 2
    For custom message add `title` attribute with the required message. – Shlomi Hassid Jun 13 '15 at 11:57
  • 8
    The same `pattern` answer has been given [a few months earlier](http://stackoverflow.com/a/10294291/1269037). How is this answer better? – Dan Dascalescu Sep 01 '15 at 00:58
  • @DanDascalescu He didn't have form tags and a clear explanation. I also included a working jsfiddle demo. (btw Stackoverflow rules say that it's not forbidden to give similar answers as long as it's helpful to the community) – Ali Çarıkçıoğlu Jan 27 '19 at 13:55
  • One way to give an even better answer is to include the demo here on SO as a [runnable code snippet](https://stackoverflow.blog/2014/09/16/introducing-runnable-javascript-css-and-html-code-snippets/). – Dan Dascalescu Jan 27 '19 at 21:15
12

Yes, there it is. It's like maxlength. W3.org documentation: http://www.w3.org/TR/html5/forms.html#attr-fe-minlength

In case minlength doesn't work, use the pattern attribute as mentioned by @Pumbaa80 for the input tag.

For textarea: For setting max; use maxlength and for min go to this link.

You will find here both for max and min.

Community
  • 1
  • 1
Sohel Ahmed Mesaniya
  • 3,344
  • 1
  • 23
  • 29
12

I used maxlength and minlength with or without required and it worked for me very well for HTML5.

<input id="passcode" type="password" minlength="8" maxlength="10">

`

benaff033
  • 129
  • 1
  • 5
6

minlength attribute is now widely supported in most of the browsers.

<input type="text" minlength="2" required>

But, as with other HTML5 features, IE11 is missing from this panorama. So, if you have a wide IE11 user base, consider using the pattern HTML5 attribute that is supported almost across the board in most browsers (including IE11).

To have a nice and uniform implementation and maybe extensible or dynamic (based on the framework that generate your HTML), I would vote for the pattern attribute:

<input type="text" pattern=".{2,}" required>

There is still a small usability catch when using pattern. The user will see a non-intuitive (very generic) error/warning message when using pattern. See this jsfiddle or below:

<h3>In each form type 1 character and press submit</h3>
</h2>
<form action="#">
  Input with minlength: <input type="text" minlength="2" required name="i1">
  <input type="submit" value="Submit">
</form>
<br>
<form action="#">
  Input with patern: <input type="text" pattern=".{2,}" required name="i1">
  <input type="submit" value="Submit">
</form>

For example, in Chrome (but similar in most browsers), you will get the following error messages:

Please lengthen this text to 2 characters or more (you are currently using 1 character)

by using minlength and

Please match the format requested

by using pattern.

Gabriel Petrovay
  • 20,476
  • 22
  • 97
  • 168
5

The minLength attribute (unlike maxLength) does not exist natively in HTML5. However, there a some ways to validate a field if it contains less than x characters.

An example is given using jQuery at this link: http://docs.jquery.com/Plugins/Validation/Methods/minlength

<html>
    <head>
        <script src="http://code.jquery.com/jquery-latest.js"></script>
        <script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>
        <script type="text/javascript">
            jQuery.validator.setDefaults({
                debug: true,
                success: "valid"
            });;
        </script>

        <script>
            $(document).ready(function(){
                $("#myform").validate({
                    rules: {
                        field: {
                            required: true,
                            minlength: 3
                        }
                    }
                });
            });
        </script>
    </head>

    <body>
        <form id="myform">
            <label for="field">Required, Minimum length 3: </label>
            <input class="left" id="field" name="field" />
            <br/>
            <input type="submit" value="Validate!" />
        </form>
    </body>

</html>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Valéry Stroeder
  • 613
  • 1
  • 6
  • 15
5

I notice that sometimes in Chrome when autofill is on and the fields are field by the autofill browser build in method, it bypasses the minlength validation rules, so in this case you will have to disable autofill by the following attribute:

autocomplete="off"

<input autocomplete="new-password" name="password" id="password" type="password" placeholder="Password" maxlength="12" minlength="6" required />
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
talsibony
  • 8,448
  • 6
  • 47
  • 46
4

Not HTML5, but practical anyway: if you happen to use AngularJS, you can use ng-minlength (or data-ng-minlength) for both inputs and textareas. See also this Plunk.

isherwood
  • 58,414
  • 16
  • 114
  • 157
mik01aj
  • 11,928
  • 15
  • 76
  • 119
4

My solution for textarea using jQuery and combining HTML5 required validation to check the minimum length.

minlength.js

$(document).ready(function(){
  $('form textarea[minlength]').on('keyup', function(){
    e_len = $(this).val().trim().length
    e_min_len = Number($(this).attr('minlength'))
    message = e_min_len <= e_len ? '' : e_min_len + ' characters minimum'
    this.setCustomValidity(message)
  })
})

HTML

<form action="">
  <textarea name="test_min_length" id="" cols="30" rows="10" minlength="10"></textarea>
</form>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Hiep Dinh
  • 654
  • 5
  • 8
4

See http://caniuse.com/#search=minlength. Some browsers may not support this attribute.


If the value of the "type" is one of them:

text, email, search, password, tel, or URL (warning: not include number | no browser support "tel" now - 2017.10)

Use the minlength(/ maxlength) attribute. It specifies the minimum number of characters.

For example,

<input type="text" minlength="11" maxlength="11" pattern="[0-9]*" placeholder="input your phone number">

Or use the "pattern" attribute:

<input type="text" pattern="[0-9]{11}" placeholder="input your phone number">

If the "type" is number, although minlength(/ maxlength) is not be supported, you can use the min(/ max) attribute instead of it.

For example,

<input type="number" min="100" max="999" placeholder="input a three-digit number">
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
levinit
  • 394
  • 3
  • 7
2

New version:

It extends the use (textarea and input) and fixes bugs.

// Author: Carlos Machado
// Version: 0.2
// Year: 2015
window.onload = function() {
    function testFunction(evt) {
        var items = this.elements;
        for (var j = 0; j < items.length; j++) {
            if ((items[j].tagName == "INPUT" || items[j].tagName == "TEXTAREA") && items[j].hasAttribute("minlength")) {
                if (items[j].value.length < items[j].getAttribute("minlength") && items[j].value != "") {
                    items[j].setCustomValidity("The minimum number of characters is " + items[j].getAttribute("minlength") + ".");
                    items[j].focus();
                    evt.defaultPrevented;
                    return;
                }
                else {
                    items[j].setCustomValidity('');
                }
            }
        }
    }
    var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
    var isChrome = !!window.chrome && !isOpera;
    if(!isChrome) {
        var forms = document.getElementsByTagName("form");
        for(var i = 0; i < forms.length; i++) {
            forms[i].addEventListener('submit', testFunction,true);
            forms[i].addEventListener('change', testFunction,true);
        }
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Carlos Machado
  • 139
  • 1
  • 3
  • Thanks for this elegant updated solution. Does it work outside of Chrome/Opera since they don't support minlength? http://caniuse.com/#search=minlength I just tested it on Mac Safari and it doesn't work :( I see you are adding the eventListener for non Chrome/Opera browsers, so maybe I am doing something wrong. – rmcsharry Oct 13 '16 at 14:05
  • After debugging Safari it seems that var items = this.elements; is returning the FORMS collection, not the items in the form. Weird. – rmcsharry Oct 13 '16 at 14:50
2

Following @user123444555621 pinned answer.

There is a minlength attribute in HTML5 but for some reason it may not always work as expected.

I had a case where my input type text did not obey the minlength="3" property.

By using the pattern attribute I managed to fix my problem. Here's an example of using pattern to ensure minlength validation:

const folderNameInput = document.getElementById("folderName");

folderNameInput.addEventListener('focus', setFolderNameValidityMessage);
folderNameInput.addEventListener('input', setFolderNameValidityMessage);

function setFolderNameValidityMessage() {
  if (folderNameInput.validity.patternMismatch || folderNameInput.validity.valueMissing) {
      folderNameInput.setCustomValidity('The folder name must contain between 3 and 50 chars');
  } else {
      folderNameInput.setCustomValidity('');
  }
}
:root {
  --color-main-red: rgb(230, 0, 0);
  --color-main-green: rgb(95, 255, 143);
}

form input {
  border: 1px solid black;
  outline: none;
}

form input:invalid:focus {
  border-bottom-color: var(--color-main-red);
  box-shadow: 0 2px 0 0 var(--color-main-red);
}

form input:not(:invalid):focus {
  border-bottom-color: var(--color-main-green);
  box-shadow: 0 2px 0 0 var(--color-main-green);
}
<form>
  <input
    type="text"
    id="folderName"
    placeholder="Your folder name"
    spellcheck="false"
    autocomplete="off"
    
    required
    minlength="3"
    maxlength="50"
    pattern=".{3,50}"
  />
  <button type="submit" value="Create folder">Create folder</button>
</form>

For further details, here's the MDN link to the HTML pattern attribute: https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/pattern

1

I wrote this JavaScript code, [minlength.js]:

window.onload = function() {
    function testaFunction(evt) {
        var elementos = this.elements;
        for (var j = 0; j < elementos.length; j++) {
            if (elementos[j].tagName == "TEXTAREA" && elementos[j].hasAttribute("minlength")) {
                if (elementos[j].value.length < elementos[j].getAttribute("minlength")) {
                    alert("The textarea control must be at least " + elementos[j].getAttribute("minlength") + " characters.");
                    evt.preventDefault();
                };
            }
        }
    }
    var forms = document.getElementsByTagName("form");
    for(var i = 0; i < forms.length; i++) {
        forms[i].addEventListener('submit', testaFunction, true);
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Carlos Machado
  • 139
  • 1
  • 3
1

In my case, in which I validate the most manually and using Firefox (43.0.4), minlength and validity.tooShort are not available unfortunately.

Since I only need to have minimum lengths stored to proceed, an easy and handy way is to assign this value to another valid attribute of the input tag. In that case then, you can use min, max, and step properties from [type="number"] inputs.

Rather than storing those limits in an array it's easier to find it stored in the same input instead of getting the element id to match the array index.

1

If desired to make this behavior, always show a small prefix on the input field or the user can't erase a prefix:

   // prefix="prefix_text"
   // If the user changes the prefix, restore the input with the prefix:
   if(document.getElementById('myInput').value.substring(0,prefix.length).localeCompare(prefix))
       document.getElementById('myInput').value = prefix;
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
1

I used max and min then required, and it worked for me very well, but what am not sure is if it is a but coding method.

<input type="text" maxlength="13" name ="idnumber" class="form-control"  minlength="13" required>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Humphrey
  • 2,659
  • 3
  • 28
  • 38
0

You can use minlength in input tag or you can regex pattern to check the number of character or even you can take the input and check the length of the character and then you can restrict based upon your requirement.

0

Smartest Way for maxlength

$("html").on("keydown keyup change", "input", function(){
    var maxlength=$(this).attr('maxlength');    
    if(maxlength){  
        var value=$(this).val();
        if(value.length<=maxlength){
            $(this).attr('v',value);
        }
        else{
            $(this).val($(this).attr('v'));
        }   
    }
});     
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" maxlength="10">
  • If you have a new question, please ask it by clicking the [Ask Question](https://stackoverflow.com/questions/ask) button. Include a link to this question if it helps provide context. - [From Review](/review/late-answers/31494183) – Ethan Apr 12 '22 at 01:15
0

I've used the follow tag with numbers:

<input type="tel" class="form-control" name="Extension" id="Extension" required maxlength="4" minlength="4" placeholder="4 Digits" />
Nasser X
  • 175
  • 3
  • 10
-4

Add both a maximum and a minimum value. You can specify the range of allowed values:

<input type="number" min="1" max="999" />
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Deepti Gehlot
  • 617
  • 7
  • 8