输入和文本区域上的 maxlength
属性对于用户输入效果很好,但是当我使用 Javascript 修改值或通过 value="..."
设置它时之后提交表单,不应用验证:
<form action="#">
<input type="text" maxlength="5" value="Longer than 5 chars">
<input type="submit">
</form>
为什么这不会失败?
与数字输入相比,表单按预期失败:
<form action="#">
<input type="number" max="4" value="8">
<input type="submit">
</form>
根据MDN ,
[maxlength] Constraint validation is only applied when the value is changed by the user.
但是为什么呢?没有Javascript可以解决这个问题吗?在两个不同的地方(第一个在 HTML 中,第二个在 Javascript 中)验证 maxlength 似乎是多余的。
此验证问题适用于哪些属性? 最大长度
、最小长度
等等...?输入数字?输入日期?是否有这些列表,以便我知道哪些需要手动验证?
编辑:这是一个更具体的用例:
function addChar() {
document.querySelector('input[type="text"]').value += 'a';
}
<form action="#">
<input type="text" maxlength="5" value="a">
<input type="submit">
</form>
<button onclick="addChar()">Add another character</button>
用户可能会单击“添加另一个字符”按钮几次,然后提交表单。它不会失败。如果我想阻止用户添加太多字符,我需要添加自定义 Javascript 验证:
function addChar() {
var input = document.querySelector('input[type="text"]');
if(input.value.length > input.maxLength) {
return;
}
input.value += 'a';
}
<form action="#">
<input type="text" maxlength="5" value="a">
<input type="submit">
</form>
<button onclick="addChar()">Add another character</button>
现在,代码中对 maxlength
进行了两次验证。与其他有效限制(如上面的数字输入 max
)相比,这似乎不正确且不一致
最佳答案
对于某些输入
类型,the pattern
attribute在这种特定情况下可能最有用,因为正如您所确定的,在约束验证方面,规范以不同的方式对待 maxlength
和 minlength
。
minlength
和 maxlength
都需要用户输入才能引发脏值标志
,从而触发无效状态,从而强制进行验证提交时。通过脚本设置值不会引发标志:
- https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#attr-fe-maxlength
- https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#concept-fe-dirty
- https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#constraints
但是,pattern
属性没有这种独特的要求,因此将在表单提交时进行验证,所以看起来,请参见下面的示例:
function addChar() {
var input = document.querySelector('input[type="text"]');
input.value += 'a';
}
input:invalid {
border: 1px solid crimson;
}
<form action="#">
<input type="text" value="a" pattern=".{1,5}" title="You may only include a maximum of 5 characters.">
<input type="submit">
</form>
<button onclick="addChar()">Add another character</button>
关于javascript - 输入类型 ="text"表单提交时忽略最大长度验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60758779/