:required
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
Lớp giả :required trong CSS (pseudo-class) đại diện cho bất kỳ phần tử <input>, <select>, hoặc <textarea> nào có thuộc tính required được đặt trên đó.
Try it
label {
display: block;
margin-top: 1em;
}
.req {
color: red;
}
*:required {
background-color: gold;
}
<form>
<label for="name">Name: <span class="req">*</span></label>
<input id="name" name="name" type="text" required />
<label for="birth">Date of Birth:</label>
<input id="birth" name="birth" type="date" />
<label for="origin"
>How did you find out about us? <span class="req">*</span></label
>
<select id="origin" name="origin" required>
<option>Google</option>
<option>Facebook</option>
<option>Advertisement</option>
</select>
<p><span class="req">*</span> - Required field</p>
</form>
Lớp giả này hữu ích để làm nổi bật các trường phải có dữ liệu hợp lệ trước khi biểu mẫu có thể được gửi.
Note:
Lớp giả :optional chọn các trường biểu mẫu tùy chọn.
Cú pháp
:required {
/* ... */
}
Khả năng truy cập
Các phần tử <input> bắt buộc nên có thuộc tính required áp dụng cho chúng. Điều này sẽ đảm bảo rằng những người điều hướng với sự hỗ trợ của công nghệ hỗ trợ tiếp cận như trình đọc màn hình sẽ có thể hiểu các input nào cần nội dung hợp lệ để đảm bảo gửi thành công.
Nếu biểu mẫu cũng chứa các input tùy chọn, các input bắt buộc nên được chỉ ra về mặt hình ảnh bằng cách xử lý không chỉ dựa vào màu sắc để truyền đạt ý nghĩa. Thông thường, văn bản mô tả và/hoặc biểu tượng được sử dụng.
Ví dụ
>Trường bắt buộc có viền đỏ
HTML
<form>
<div class="field">
<label for="url_input">Enter a URL:</label>
<input type="url" id="url_input" />
</div>
<div class="field">
<label for="email_input">Enter an email address:</label>
<input type="email" id="email_input" required />
</div>
</form>
CSS
label {
display: block;
margin: 1px;
padding: 1px;
}
.field {
margin: 1px;
padding: 1px;
}
input:required {
border-color: maroon;
border-width: 3px;
}
input:required:invalid {
border-color: #c00000;
}
Kết quả
Thông số kỹ thuật
| Specification |
|---|
| HTML> # selector-required> |
| Selectors Level 4> # required-pseudo> |
Tương thích trình duyệt
Xem thêm
- Các lớp giả liên quan đến xác thực khác:
:optional,:invalid,:valid - Form data validation