检查有效性/报告Vality对于通过代码设置的值不起作用



如果通过JavaScript设置值,HTML5checkValidity()/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>

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

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

我调查了一段时间。似乎您至少缺少包装输入+按钮内容<form>

但是,即使我尝试设置输入字段required,ValidityObject仍然不会注意到超过了长度。

作为半解决方法,我提出了使用pattern属性的想法:

<input id='textfield' pattern='S{0,3}'>

(=\S代表"除空格外的所有字符"(

这至少会阻止超过三个字符的内容。此外,您可以针对无效案例setCustomValidity消息。

请参阅以下工作示例:https://codepen.io/zvona/pen/rNavqxP?editors=1010

我尝试了一些事情,使我明白checkValid不会检查值本身。

当我点击 #check 有效性时,我得到:

textField.validity.tooLong // false
textField.validity.valid // true
textField.value // This is a very looooooooooooooooooooooooooooooong text

当我在输入中输入自己时,我的浏览器不允许我输入超过 3 个字符。

为什么?

确切地说,我不知道,但是有一篇关于约束验证的很棒的文章值得一看。

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

textField.value 返回您的字符串,然后您可以访问它的长度。在这种情况下,无论如何我都会更喜欢这种方式。

const tooLong = textField.value.length > 3;
if (tooLong) window.alert('Something');

我希望它有所帮助。

您应该检查表单是否有效,而不是输入有效。但似乎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
};
};
<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>

不过,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());
};
};
<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>

最新更新