Thuộc tính HTML <input> pattern
Thí dụ
Biểu mẫu HTML có trường nhập chỉ có thể chứa ba chữ cái (không có số hoặc ký tự đặc biệt):
<form action="/action_page.php">
<label for="country_code">Country code:</label>
<input
type="text" id="country_code" name="country_code"
pattern="[A-Za-z]{3}"
title="Three letter country code"><br><br>
<input type="submit">
</form>
Thêm các ví dụ "Hãy tự mình thử" bên dưới.
Định nghĩa và Cách sử dụng
Thuộc pattern
tính chỉ định một biểu thức chính quy mà
<input>
giá trị của phần tử được kiểm tra khi gửi biểu mẫu.
Lưu ý: Thuộc pattern
tính hoạt động với các loại đầu vào sau: văn bản, ngày tháng, tìm kiếm, url, số điện thoại, email và mật khẩu.
Mẹo: Sử dụng thuộc tính global title
để mô tả mẫu giúp người dùng.
Mẹo: Tìm hiểu thêm về biểu thức chính quy trong hướng dẫn JavaScript của chúng tôi.
Hỗ trợ trình duyệt
Các số trong bảng chỉ định phiên bản trình duyệt đầu tiên hỗ trợ đầy đủ thuộc tính.
Attribute | |||||
---|---|---|---|---|---|
pattern | 5.0 | 10.0 | 4.0 | 10.1 | 9.6 |
Cú pháp
<input pattern="regexp">
Giá trị thuộc tính
Value | Description |
---|---|
regexp | Specifies a regular expression that the <input> element's value is checked against |
Các ví dụ khác
Thí dụ
Phần tử <input> có type = "password" phải chứa 8 ký tự trở lên:
<form action="/action_page.php">
<label for="pwd">Password:</label>
<input type="password" id="pwd"
name="pwd"
pattern=".{8,}" title="Eight or more characters">
<input type="submit">
</form>
Thí dụ
Phần tử <input> có type = "password" phải chứa 8 ký tự trở lên có ít nhất một số và một chữ hoa và chữ thường:
<form action="/action_page.php">
<label for="pwd">Password:</label>
<input type="password" id="pwd" name="pwd"
pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}"
title="Must contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters">
<input type="submit">
</form>
Thí dụ
Phần tử <input> có type = "email" phải theo thứ tự sau: ký tự @ ký tự . miền (các ký tự theo sau là dấu @, theo sau là các ký tự khác, rồi đến dấu "."
Sau "." ký, thêm ít nhất 2 chữ cái từ a đến z:
<form action="/action_page.php">
<label
for="email">Email:</label>
<input type="email" id="email" name="email"
pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$">
<input type="submit">
</form>
Thí dụ
Phần tử <input> có type = "search" KHÔNG THỂ chứa các ký tự sau: 'hoặc "
<form action="/action_page.php">
<label
for="search">Search:</label>
<input type="search" id="search" name="search"
pattern="[^'\x22]+" title="Invalid input">
<input type="submit">
</form>
Thí dụ
Phần tử <input> có type = "url" phải bắt đầu bằng http: // hoặc https: // theo sau là ít nhất một ký tự:
<form action="/action_page.php">
<label
for="website">Homepage:</label>
<input type="url" id="website"
name="website"
pattern="https?://.+" title="Include http://">
<input type="submit">
</form>
❮ Thẻ HTML <input>