ใช้แอตทริบิวต์ min เพื่อกำหนดค่าต่ำสุดที่รับได้ใน HTML ใช้กับ Input types ที่เป็นตัวเลข/วันที่
ตัวอย่าง
ลองรันโค้ดต่อไปนี้เพื่อใช้งานแอตทริบิวต์ min:
<!DOCTYPE html>
<html>
<body>
<form action="">
Rank: <input type="number" name="rank" min="1" max="10"><br>
<input type="submit">
</form>
</body>
</html>
Input Types ที่รองรับ min
| Type | รูปแบบค่า min | ตัวอย่าง |
|---|---|---|
number |
Integer/Float | min="0", min="-10", min="1.5" |
range |
Integer/Float | min="0" |
date |
YYYY-MM-DD | min="2024-01-01" |
month |
YYYY-MM | min="2024-01" |
week |
YYYY-Www | min="2024-W01" |
datetime-local |
YYYY-MM-DDThh:mm | min="2024-01-01T00:00" |
time |
hh:mm | min="09:00" |
ตัวอย่างการใช้งานหลากหลาย
<!-- อายุ ต้องมากกว่าหรือเท่ากับ 18 -->
<input type="number" name="age" min="18" max="120" placeholder="Age">
<!-- วันที่จอง ต้องไม่ใช่วันในอดีต -->
<input type="date" name="booking_date" min="2024-12-20">
<!-- เวลาทำการ 09:00 - 18:00 -->
<input type="time" name="appointment" min="09:00" max="18:00">
<!-- Slider ราคา 0 - 10000 -->
<input type="range" name="price" min="0" max="10000" step="100">
<!-- สัปดาห์ในปี 2024 -->
<input type="week" name="week" min="2024-W01" max="2024-W52">
การใช้งานร่วมกับ max และ step
<input type="number" name="quantity" min="1" max="100" step="1" value="1">
<input type="range" name="volume" min="0" max="100" step="5" value="50">
Validation และ JavaScript
<input type="number" id="age" name="age" min="18" required>
<script>
const input = document.getElementById('age');
// HTML5 Validation อัตโนมัติ: จะบล็อก submit ถ้าน้อยกว่า 18
// ตรวจสอบด้วย JS
input.addEventListener('input', function() {
if (this.validity.rangeUnderflow) {
this.setCustomValidity(`Must be at least ${this.min}`);
} else {
this.setCustomValidity('');
}
});
// อ่านค่า min/max ผ่าน JS
console.log(input.min, input.max, input.step);
</script>
Dynamic Min (JavaScript)
<input type="date" id="startDate">
<input type="date" id="endDate" min="">
<script>
const start = document.getElementById('startDate');
const end = document.getElementById('endDate');
start.addEventListener('change', () => {
end.min = start.value; // end date ต้องมากกว่าหรือเท่ากับ start date
if (end.value && end.value < start.value) {
end.value = start.value;
}
});
</script>