Thuộc tính pattern trong HTML định nghĩa một biểu thức chính quy (regex) để kiểm tra giá trị của phần tử <input> khi submit form.
Cú pháp
<input pattern="biểu_thức_chính_quy">
Ví dụ
Ví dụ yêu cầu mật khẩu tối thiểu 8 ký tự:
<!DOCTYPE html>
<html>
<style>
body {
color: #000;
height: 100vh;
background: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%) no-repeat;
text-align: center;
}
input[type='password'] {
width: 300px;
padding: 8px 16px;
border: 2px solid #fff;
background: transparent;
border-radius: 20px;
display: block;
margin: 1rem auto;
outline: none;
}
.btn {
background: #db133a;
border: none;
height: 2rem;
border-radius: 20px;
width: 330px;
display: block;
color: #fff;
outline: none;
cursor: pointer;
margin: 1rem auto;
}
::placeholder { color: #000; }
</style>
<body>
<h1>Ví dụ thuộc tính pattern</h1>
<form action="">
<input type="password" placeholder="Nhập mật khẩu tài khoản" required pattern=".{8,}">
<input type="submit" value="Gửi" class="btn">
</form>
<div class="show"></div>
</body>
</html>
Kết quả
Nhập mật khẩu dưới 8 ký tự và nhấn "Gửi" → trình duyệt hiển thị cảnh báo yêu cầu ít nhất 8 ký tự.
Mẹo: Sử dụng title để thêm thông báo tùy chỉnh: title="Mật khẩu phải có ít nhất 8 ký tự"