:invalid

摘要

:invalid CSS 伪类(CSS pseudo-class )表示任何 <input> 或 <form> 元素的内容无法通过输入的类型设置的验证。 这使您可以轻松设置无效字段的外观,帮助用户识别并更正错误。

默认情况下,Gecko 不会对:invalid 伪类应用样式。However it does apply a style (a red "glow" using the box-shadow property) to the :-moz-ui-invalid pseudo-class, which applies in a subset of cases for :invalid.

您可以使用下面的 CSS来禁用发光或完全重写它以改变无效字段的外观。

:invalid {
    box-shadow: none;
}
:-moz-submit-invalid {
    box-shadow: none;
}
:-moz-ui-invalid {
    box-shadow:none;
}

语法

:invalid { style properties }

注意

单选按钮组

只要单选按钮组中(即拥有相同name属性的单选按钮) 任意一个按钮是必选的,  当所有的单选按钮都未被选中时:invalid 伪类将会被应用到按钮组中的所有的按钮上.译者注:当然前提是必须是浏览器不是ie,ie上则是谁上面有require谁使用该伪类,其余的按钮无变化

例子

例子展示一个简单的表单,通过验证的表单元素为绿色,未通过验证的为红色.

HTML Content

<form>
  <label>Enter a URL:</label>
  <input type="url" />
  <br />
  <br />
  <label>Enter an email address:</label>
  <input type="email" required/>
</form>

CSS Content

input:invalid {
  background-color: #ffdddd;
}
form:invalid {
  border: 5px solid #ffdddd;
}
input:valid {
  background-color: #ddffdd;
}
form:valid {
  border: 5px solid #ddffdd;
}
input:required {
  border-color: #800000;
  border-width: 3px;
}
input:required:invalid {
  border-color: #C00000;
}

规范

Specification Status Comment
WHATWG HTML Living Standard
:invalid
Living Standard No change.
HTML5
:invalid
Recommendation Defines the semantic regarding HTML and constraint validation.
Selectors Level 4
:invalid
Working Draft No change.
CSS Basic User Interface Module Level 3
:invalid
Candidate Recommendation Defines the pseudo-class, but not the associated semantic.

浏览器兼容性

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (<input>) 10.0 4.0 (2) 10 10.0 5.0
Apply it to <form> ? 13 (13) ? ? ?
Feature Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support ? 4.0 (2) 未实现 10.0 5.0
Apply it to <form> ? 13.0 (13) ? ? ?

参见

文档标签和贡献者