ใช้แอตทริบิวต์ pattern เพื่อกำหนด Regular Expression (Regex) ที่ค่าของ <input> จะถูกตรวจสอบตาม
ตัวอย่าง
ลองรันโค้ดต่อไปนี้เพื่อใช้งานแอตทริบิวต์ pattern:
<!DOCTYPE html>
<html>
<head>
<title>HTML pattern attribute</title>
</head>
<body>
<form action="" method="get" novalidate>
Student Name<br><input type="text" name="sname" required><br>
Rank<br><input type="number" name="rank"><br>
Student Country Code (3 letters) <br>
<input type="text" name="ccode" pattern="[A-Za-z]{3}"
title="Country code: 3 letters (e.g. THA, USA)" required><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Pattern Regex Patterns ที่นิยมใช้
| รูปแบบ | Pattern | ตัวอย่างที่ผ่าน |
|---|---|---|
| ตัวอักษร 3 ตัว (Country code) | [A-Za-z]{3} |
THA, USA, JPN |
| Username (อักษร/ตัวเลข/_-) 3-20 ตัว | [A-Za-z0-9_-]{3,20} |
john_doe, user123 |
| Email (พื้นฐาน) | [^@\s]+@[^@\s]+\.[^@\s]+ |
user@example.com |
| Phone Thailand (08x-xxx-xxxx) | 0[689][0-9]{8} |
0812345678, 0987654321 |
| รหัสไปรษณีย์ไทย (5 หลัก) | [0-9]{5} |
10100, 50000 |
| บัตรประชาชน (13 หลัก) | [0-9]{13} |
1234567890123 |
| Password (8+ ชาร์ท, มีตัวใหญ่ เล็ก ตัวเลข) | ^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$ |
Pass1234, MyPass123 |
| Hex Color | ^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$ |
#ff0000, #abc |
| IPv4 Address | ^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$ |
192.168.1.1 |
แอตทริบิวต์ title (สำคัญ)
title ใช้แสดงข้อความแนะนำเมื่อ Validation ล้มเหลว (Tooltip/Error Message)
<input pattern="[0-9]{5}" title="Please enter 5-digit zip code">
การใช้งานกับ Input Types ต่างๆ
<!-- Text -->
<input type="text" pattern="[A-Za-z]+" title="Letters only">
<!-- Tel (เบอร์โทร) -->
<input type="tel" pattern="0[689][0-9]{8}" title="Thai mobile: 08x-xxx-xxxx">
<!-- Password -->
<input type="password" pattern=".{8,}" title="Min 8 characters">
<!-- Search -->
<input type="search" pattern="[^<>]*" title="No HTML tags">
JavaScript: ตรวจสอบ Pattern ด้วยตนเอง
const input = document.querySelector('input[pattern]');
const regex = new RegExp(input.pattern);
input.addEventListener('input', () => {
const valid = regex.test(input.value);
input.setCustomValidity(valid ? '' : input.title || 'Invalid format');
});
CSS สำหรับ Pattern Validation
input[pattern]:invalid:not(:placeholder-shown) {
border-color: #dc3545;
background-image: url("data:image/svg+18,...");
}
input[pattern]:valid:not(:placeholder-shown) {
border-color: #28a745;
}
หมายเหตุ: Pattern ไม่ทำงานกับ type="email", "url", "number" (มี Validation ของตัวเอง) ใช้กับ text, tel, password, search เป็นหลัก