Thuộc tính maxlength chỉ định số ký tự tối đa cho phép nhập vào một phần tử <input> hoặc <textarea>.
Cú pháp
<input maxlength="số_nguyên"> <textarea maxlength="số_nguyên"></textarea>
Ví dụ
<!DOCTYPE html>
<html>
<style>
body { color: #000; height: 100vh; background-color: #8BC6EC; background-image: linear-gradient(135deg, #8BC6EC 0%, #9599E2 100%); text-align: center; }
input { width: 300px; background: transparent; border: 2px solid #fff; outline: none; display: block; margin: 1rem auto; border-radius: 20px; padding: 8px 10px; }
::placeholder { color: #000; }
.btn { background: #db133a; color: #fff; border: none; width: 320px; padding: 10px; border-radius: 20px; cursor: pointer; }
</style>
<body>
<h1>Demo maxlength</h1>
<form action="">
<input type="text" placeholder="Tên (tối đa 8 ký tự)" maxlength="8" required>
<input type="submit" value="GỬI" class="btn">
</form>
</body>
</html>
Kết quả
Thử nhập hơn 8 ký tự → trình duyệt chặn không cho nhập thêm (con trỏ dừng lại).
Lưu ý: maxlength chỉ validation client-side. Luôn validate lại server-side. Dùng minlength cho độ dài tối thiểu. Trên textarea cũng hoạt động tương tự.