:valid - CSS: Cascading Style Sheets 编辑

The :valid CSS pseudo-class represents any <input> or other <form> element whose contents validate successfully. This allows to easily make valid fields adopt an appearance that helps the user confirm that their data is formatted properly.

/* Selects any valid <input> */
input:valid {
  background-color: powderblue;
}

This pseudo-class is useful for highlighting correct fields for the user.

Syntax

:valid

Examples

Indicating valid and invalid form fields

In this example, we use structures like this, which include extra <span>s to generate content on; we'll use these to provide indicators of valid/invalid data:

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

To provide these indicators, we use the following 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;
}

We set the <span>s to position: relative so that we can position the generated content relative to them. We then absolutely position different generated content depending on whether the form's data is valid or invalid — a green check or a red cross, respectively. To add a bit of extra urgency to the invalid data, we've also given the inputs a thick red border when invalid.

Note: We've used ::before to add these labels, as we were already using ::after for the "required" labels.

You can try it below:

Notice how the required text inputs are invalid when empty, but valid when they have something filled in. The email input on the other hand is valid when empty, as it is not required, but invalid when it contains something that is not a proper email address.

Accessibility concerns

The color green is commonly used to indicate valid input. People who have certain types of color blindness will be unable to determine the input's state unless it is accompanied by an additional indicator that does not rely on color to convey meaning. Typically, descriptive text and/or an icon are used.

Specifications

SpecificationStatusComment
HTML Living Standard
The definition of ':valid' in that specification.
Living StandardNo change.
HTML5
The definition of ':valid' in that specification.
RecommendationDefines the semantics of HTML and constraint validation.
Selectors Level 4
The definition of ':valid' in that specification.
Working DraftInitial definition.

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:99 次

字数:5944

最后编辑:7年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文