【问题标题】:HTML5 constraint-validation fails when data is pre-filled预填充数据时 HTML5 约束验证失败
【发布时间】:2018-01-05 07:13:56
【问题描述】:

我目前正在为 HTML5 约束验证而苦苦挣扎。

鉴于这个简单的形式:

<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 的值,它就不会提交。

但是,当将该值设置为超过 10 个字符时,表单会正常提交。

<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

当我需要编辑某些内容并且必须用可能失败的数据预填充字段时会出现问题(因为要求已更改)。 在数据更改为有效之前,它不应允许用户提交数据(即使之前存储为有效)。

为什么处理了required 验证,但没有处理maxlength?是否有任何已知的解决方法?

【问题讨论】:

标签: html validation


【解决方案1】:

maxlength 似乎只有在对&lt;input&gt; 元素的内容进行一些更改后才能工作。你也可以使用pattern来定义&lt;input&gt;的最大长度:

<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/en-US/docs/Web/HTML/Element/input#attr-maxlength

约束验证:如果一个元素具有最大允许值长度,它的脏值标志为真,它的值最后一次由用户编辑更改(与脚本所做的更改相反) , 并且元素的 API 值的 JavaScript 字符串长度大于元素的最大允许值长度,则元素过长。
来源: https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#attr-fe-maxlength

【讨论】:

    猜你喜欢
    • 2019-03-13
    • 1970-01-01
    • 2021-03-10
    • 1970-01-01
    • 1970-01-01
    • 2015-05-08
    • 1970-01-01
    • 1970-01-01
    • 2014-03-29
    相关资源
    最近更新 更多