บทนำ
แอตทริบิวต์ required ระบุว่าช่องกรอก ต้องกรอกก่อนส่งฟอร์ม ใช้ได้กับ <input>, <select>, <textarea>
ตัวอย่างโค้ด
<!DOCTYPE html>
<html>
<head>
<title>HTML Required Attribute</title>
</head>
<body>
<h2>สมัครสมาชิก</h2>
<form action="/new.php">
<input type="text" placeholder="ชื่อผู้ใช้" name="name" required><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Input Types ที่รองรับ
- text, search, url, tel, email, password
- date, month, week, time, datetime-local, number
- checkbox, radio, file
<select>,<textarea>
พฤติกรรม
- Browser แสดง Error Bubble: "Please fill out this field" ใช้ CSS
- JavaScript:
element.checkValidity(),element.reportValidity() - Submit Event ไม่ยิงถ้า Invalid
:invalid จัดสไตล์ฟิลด์ที่ผิด
Custom Error Message
<input type="email" required
oninvalid="this.setCustomValidity('กรุณากรอกอีเมลที่ถูกต้อง')"
oninput="this.setCustomValidity('')">