Is there a minlength validation attribute in HTML5?

前端 未结 17 1476
日久生厌
日久生厌 2020-11-22 17:10

It seems the minlength attribute for an field doesn\'t work.

Is there any other attribute in HTML5 with the help of which I

相关标签:
17条回答
  • 2020-11-22 17:18

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

    `

    0 讨论(0)
  • 2020-11-22 17:20

    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);
        }
    }
    
    0 讨论(0)
  • 2020-11-22 17:21

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

    <input type="number" min="1" max="999" />
    
    0 讨论(0)
  • 2020-11-22 17:23

    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;
    
    0 讨论(0)
  • 2020-11-22 17:25

    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)">
    
    0 讨论(0)
  • 2020-11-22 17:25

    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.

    0 讨论(0)
提交回复
热议问题