แอตทริบิวต์ pattern ของ HTML ใช้กำหนดนิพจน์ปกติ (regular expression) ที่ค่าขององค์ประกอบ <input> จะถูกตรวจสอบในเอกสาร HTML
ไวยากรณ์
ไวยากรณ์มีดังนี้ −
<input pattern="regular expression">
ลองดูตัวอย่างการใช้งานแอตทริบิวต์ pattern ของ HTML −
ตัวอย่าง
<!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>ตัวอย่างแอตทริบิวต์ pattern ของ HTML</h1> <form action=""> <input type="password" placeholder="ป้อนรหัสผ่านบัญชีของคุณ" required pattern=".{8,}"> <input type="submit" value="ส่ง" class="btn" onclick='check()'> </form> <div class="show"></div> <script> function check() { if (document.querySelector("input[type='password']").value.length < 8) { document.querySelector(".show").innerHTML = 'กรุณาป้อนรหัสผ่านอย่างน้อย 8 ตัวอักษร.' }; } </script> </body> </html>
ผลลัพธ์
ป้อนรหัสผ่านที่มีน้อยกว่า 8 ตัวอักษร แล้วคลิกปุ่ม ส่ง เพื่อแสดงข้อความเตือน −

