Is there a minlength validation attribute in HTML5?

前端 未结 17 1742
日久生厌
日久生厌 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 17:36

    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);
            }
        }
    }
    

提交回复
热议问题