checkValidity / reportVality 不适用于通过代码设置的值

Mic*_*ati 5 html javascript

如果通过 JavaScript 设置值, HTML5 checkValidity()/reportValidity()方法似乎不起作用。

考虑这个例子(JSFiddle):

<input id="text-field" maxlength="3" placeholder="Max len: 3 chars" />
<button id="set-field-value">Set</button>
<button id="check-valid">Is valid?</button>
<script>
window.onload = function() {
    var textField = document.getElementById('text-field');
    document.getElementById('set-field-value').onclick = function() {
        textField.value = 'This is a very looooooooooooooooooooooooooooooong text';
    };
    document.getElementById('check-valid').onclick = function() {
        window.alert(textField.checkValidity());
    };
};
</script>
Run Code Online (Sandbox Code Playgroud)

如果单击该Set按钮,输入字段的值将设置为无效值(长度大于 3 个字符),但该checkValidity()方法仍然表明输入有效(在 Chrome、Edge 和 Firefox 上检查)。

为什么?有没有办法确定该字段是否有效,即使其值是通过代码设置的?

A. *_*shu 0

您应该检查表单是否有效而不是输入。但似乎该maxLength属性根本不是触发验证的东西......

如果你想检查输入文本的长度,你可以这样做:

window.onload = function() {
  var textField = document.getElementById('text-field');
  document.getElementById('set-field-value').onclick = function() { textField.value = 'ab'; };
  document.getElementById('check-valid').onclick = function() {
    if (textField.value && // if exist AND
      textField.value.length > 2 && // if value have 3 charecter at least
      textField.value.trim().length > 2 // if value is not just spaces 
    ) {alert ('input OK');} // alert that input ok
    else { alert('please insert at least 3 charecters');} // else alert error
  };
};
Run Code Online (Sandbox Code Playgroud)
<form id="formCheck">
  <input type="text" id="text-field" min="3" />
  <button type="button" id="set-field-value">Set</button>
  <button type="button" id="check-valid">Is valid?</button>
</form>
Run Code Online (Sandbox Code Playgroud)

checkValidity()方法在此示例中按预期工作(使用输入数字和min属性):

window.onload = function() {
  var theForm =  document.getElementById('formCheck');
  var numberField = document.getElementById('number-field');
  document.getElementById('set-field-value').onclick = function() { numberField.value = '2'; };
  document.getElementById('check-valid').onclick = function() {
    window.alert(theForm.checkValidity());
  };
};
Run Code Online (Sandbox Code Playgroud)
<form id="formCheck">
<input type="number" id="number-field" min="3" />
<button type="button" id="set-field-value">Set</button>
<button type="button" id="check-valid">Is valid?</button>
</form>
Run Code Online (Sandbox Code Playgroud)