Html5 使用必需元素和禁用元素进行表单验证

Html5 form validation with required and disabled element

我知道你永远不应该禁用一个元素并且还需要它,因为如果它被禁用,用户如何让它有效?

但是,我有 <select> 种产品供用户选择。当它们 select 一种产品时,另一种 <select> 产品型号的另一个 <select> 被填充、启用并且需要 仅当产品有一个或多个型号时 。否则,模型 select 将被禁用并清空。

虽然我喜欢认为我的代码是完美的并且我可以使模型下拉列表永远不会被禁用并且同时需要,但我并不完美。那么,是否可以提交带有禁用且必需的 <select> 的表单?

更新

摘自w3.org:

Constraint validation: If the element is required, and its value IDL attribute applies and is in the mode value, and the element is mutable, and the element's value is the empty string, then the element is suffering from being missing.

查看了“可变”的具体含义。

A form control can be designated as mutable.

Note: This determines (by means of definitions and requirements in this specification that rely on whether an element is so designated) whether or not the user can modify the value or checkedness of a form control, or whether or not a control can be automatically prefilled.

选择没有值,因此由其选项决定。

The select element does not have a value; the selectedness of its option elements is what is used instead.

所以,我认为这意味着如果 <select> 元素被禁用并且是必需的,那么表单可以被认为是有效的?

http://www.w3.org/TR/html5/forms.html#enabling-and-disabling-form-controls:-the-disabled-attribute:

Constraint validation: If an element is disabled, it is barred from constraint validation.

http://www.w3.org/TR/html5/forms.html#barred-from-constraint-validation:

A submittable element is a candidate for constraint validation except when a condition has barred the element from constraint validation.

最后,从约束验证步骤列表中,http://www.w3.org/TR/html5/forms.html#constraint-validation:

3.1: If field is not a candidate for constraint validation, then move on to the next element.


这意味着,当检查表单有效性时,禁用的元素将被“忽略”。

它不会触发任何错误,也不会影响其所属表单的验证状态。