预填充数据时HTML5约束验证失败 [英] HTML5 constraint-validation fails when data is pre-filled
问题描述
我目前正在努力进行HTML5约束验证.
I'm currently struggeling with HTML5 constraint validation.
给出以下简单形式:
<form action="/" method="post">
<input type="text" name="comeGetSome" value="" required="required" maxlength="10" /><br />
<input type="submit" value="Send me" />
</form>
请参见 https://www.w3schools.com/code/tryit. asp?filename = FN6R3PLQ7A3D
只要给comeGetSome
指定了一个值就可以了.
It will not submit as long as there is a value given for comeGetSome
which is fine.
但是,将值设置为超过10个字符时,表单将很好地提交.
However, when setting the value to something longer than 10 characters, the form will submit just fine.
<form action="/" method="post">
<input type="text" name="comeGetSome" value="This is way too long" required="required" maxlength="10" /><br />
<input type="submit" value="Send me" />
</form>
请参见 https://www.w3schools.com/code/tryit. asp?filename = FN6R4H30WQI2
当我需要编辑某些内容并且必须使用数据填充字段时,可能会发生问题(因为要求已更改). 在数据更改为有效之前,不应允许用户提交数据(即使之前存储为有效).
The problem occurs when I have something I need to edit and fields have to be prefilled with data thay may fail (as of requirements have been changed). It should not allow the user to submit the data (even if stored as valid before) until the data is changed to be valid.
为什么要处理required
验证,但不能处理maxlength
?有任何已知的解决方法吗?
Why is the required
validation handled, but maxlength
is not? Are there any known workarounds?
推荐答案
maxlength
似乎仅在对<input>
元素的内容进行了一些更改之后才起作用.您也可以使用pattern
定义<input>
的最大长度:
The maxlength
seems only to work after some changes are done on the content of the <input>
element. You can also use pattern
to define the maxlength of the <input>
:
<form action="/" method="post">
<input type="text" name="comeGetSome" value="This is way too long" required="required" pattern=".{1,10}" /><br />
<input type="submit" value="Send me" />
</form>
仅当属性值已更改时才评估约束.
来源: https ://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/input#attr-maxlength
The constraint is evaluated only when the value of the attribute has been changed.
source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-maxlength
约束验证:如果元素具有最大允许值长度,则其脏值标志为true,则其值最后由用户编辑更改(与脚本所做的更改相反) ,并且元素的API值的JavaScript字符串长度大于元素的最大允许值长度,则该元素太长.
来源: https ://html.spec.whatwg.org/multipage/form-control-infrastructure.html#attr-fe-maxlength
Constraint validation: If an element has a maximum allowed value length, its dirty value flag is true, its value was last changed by a user edit (as opposed to a change made by a script), and the JavaScript string length of the element's API value is greater than the element's maximum allowed value length, then the element is suffering from being too long.
source: https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#attr-fe-maxlength
这篇关于预填充数据时HTML5约束验证失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!