developer tip

HTML5에 minlength 유효성 검사 속성이 있습니까?

copycodes 2020. 10. 3. 11:00
반응형

HTML5에 minlength 유효성 검사 속성이 있습니까?


필드 minlength속성 <input>이 작동하지 않는 것 같습니다 .

필드 값의 최소 길이를 설정할 수있는 HTML5에 다른 속성이 있습니까?


pattern속성을 사용할 수 있습니다 . required속성은 또한 그렇지 않으면 빈 값 입력 필드에서 제외됩니다, 필요한 제약 조건 확인 .

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

"빈 또는 최소 길이"에 대한 패턴을 사용하는 옵션을 만들려면 다음을 수행 할 수 있습니다.

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

이다minlength 재산 HTML5 스펙 지금뿐만 아니라 validity.tooShort인터페이스.

이제 모든 최신 브라우저의 최신 버전에서 둘 다 활성화되었습니다. 자세한 내용은 https://caniuse.com/#search=minlength를 참조 하십시오 .


다음은 HTML5 전용 솔루션입니다 (최소 길이 5, 최대 길이 10 문자 유효성 검사를 원하는 경우).

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

<form>
  <input pattern=".{5,10}">
  <input type="submit" value="Check"></input>
</form>

네, 있습니다. 그것은 maxlength와 같습니다. W3.org 문서 : http://www.w3.org/TR/html5/forms.html#attr-fe-minlength

minlength작동하지 않는 경우 태그 pattern에 @ Pumbaa80에서 언급 한 속성을 사용하십시오 input.

텍스트 영역 : 최대 설정 용; 사용 maxlength하고 분 동안 이 링크 로 이동 하십시오 .

여기에서 최대 및 최소를 찾을 수 있습니다.


minLength 속성 (maxLength와 달리)은 HTML5에 기본적으로 존재하지 않습니다. 그러나 x 자 미만의 필드를 포함하는 경우 필드의 유효성을 검사하는 몇 가지 방법이 있습니다.

이 링크에서 jQuery를 사용하여 예제가 제공됩니다. 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>

HTML5는 아니지만 어쨌든 실용적입니다. AngularJS 를 사용 ng-minlength하는 경우 입력 및 텍스트 영역 모두에 사용할 수 있습니다 . 이 Plunk를 참조하십시오 .


jQuery를 사용하고 HTML5를 결합하여 최소 길이를 확인하는 데 필요한 텍스트 영역에 대한 솔루션입니다.

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>

나는 maxlength와 minlength를 유무에 관계없이 사용 required했으며 HTML5에서 매우 잘 작동했습니다.

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

`


새로운 버전:

사용 (텍스트 영역 및 입력)을 확장하고 버그를 수정합니다.

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

I notice that sometimes in chrome when autofill is on and the fields are field by the autofill browser build in method, it bypass 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 />

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 minlength(/ maxlength) attribute , it specifies the minimum number of characters.

eg.

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

or use "pattern" attribute:

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

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

eg.

<input type="number" min="100" max="999" placeholder="input a three-digit number">

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.


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

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;

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

<input type="text" maxlength="13" name ="idnumber" class="form-control"  minlength="13" required>

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.


Add both a max and a min value you can specify the range of allowed values:

<input type="number" min="1" max="999" />

참고URL : https://stackoverflow.com/questions/10281962/is-there-a-minlength-validation-attribute-in-html5

반응형