Is there a minlength validation attribute in HTML5

2019-01-01 04:06发布

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

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

16条回答
有味是清欢
2楼-- · 2019-01-01 04:46

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>
查看更多
流年柔荑漫光年
3楼-- · 2019-01-01 04:46

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

But 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 of other properly from non-text type inputs (type="number"), but still 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.

查看更多
刘海飞了
4楼-- · 2019-01-01 04:47

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.

查看更多
梦寄多情
5楼-- · 2019-01-01 04:48

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

查看更多
初与友歌
6楼-- · 2019-01-01 04:48

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);
    }
}
查看更多
高级女魔头
7楼-- · 2019-01-01 04:49

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

   //prefix="prefix_text"
   //if the user change the prefix, restore the input with the prefix:
   if(document.getElementById('myInput').value.substring(0,prefix.length).localeCompare(prefix)) 
       document.getElementById('myInput').value = prefix;
查看更多
登录 后发表回答