:valid

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

:valid CSS 伪类表示任何内容<input>或其他<form>元素验证成功的元素。这使得有效的字段可以很容易地采用一种外观,帮助用户确认他们的数据格式正确。

试一试

label {
  display: block;
  margin-top: 1em;
}

input:valid {
  background-color: ivory;
  border: none;
  outline: 2px solid deepskyblue;
  border-radius: 5px;
  accent-color: gold;
}
<form>
  <label for="email">Email Address:</label>
  <input id="email" name="email" type="email" value="na@me@example.com" />

  <label for="secret">Secret Code: (lower case letters)</label>
  <input id="secret" name="secret" type="text" value="test" pattern="[a-z]+" />

  <label for="age">Your age: (18+)</label>
  <input id="age" name="age" type="number" value="5" min="18" />

  <label
    ><input name="tos" type="checkbox" required checked /> - Do you agree to
    ToS?</label
  >
</form>

这个伪类对于为用户突出显示正确字段很有用。

语法

css
:valid {
  /* ... */
}

无障碍

绿色通常用于表示有效输入。患有某些类型色盲的人将无法确定输入的状态,除非它伴有不依赖颜色传达意义的额外指示。通常使用描述性文本和/或图标。

示例

指示有效和无效的表单字段

在这个例子中,我们使用这样的结构,其中包含额外的 <span> 来生成内容;我们将使用它们来提供有效/无效数据的指示器。

html
<div>
  <label for="fname">First name *: </label>
  <input id="fname" name="fname" type="text" required />
  <span></span>
</div>

为了提供这些指示器,我们使用以下 CSS

css
input + span {
  position: relative;
}

input + span::before {
  position: absolute;
  right: -20px;
  top: 5px;
}

input:invalid {
  border: 2px solid red;
}

input:invalid + span::before {
  content: "✖";
  color: red;
}

input:valid + span::before {
  content: "✓";
  color: green;
}

我们将 <span> 设置为 position: relative,以便我们可以相对地定位生成的内容。然后我们根据表单数据是有效还是无效来绝对定位不同的生成内容——分别是绿色对勾或红色叉号。为了给无效数据增加一点紧迫感,我们还在无效时给输入框设置了粗红色边框。

注意:我们使用 ::before 来添加这些标签,因为我们已经使用 ::after 来添加“必填”标签。

您可以在下面尝试

请注意,必填文本输入在为空时无效,但在填充内容时有效。另一方面,电子邮件输入在为空时有效,因为它不是必填项,但当它包含的不是正确电子邮件地址时则无效。

规范

规范
HTML
# 选择器-有效
选择器 Level 4
# 有效-伪类

浏览器兼容性

另见