Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> HTML

Thuộc tính required của Input Month trong HTML DOM

Thuộc tính required của <input type="month"> cho phép trả về hoặc thiết lập việc bắt buộc người dùng phải chọn tháng trước khi submit form.

Cú pháp

Lấy giá trị:

monthInput.required

Thiết lập giá trị:

monthInput.required = true | false

Ví dụ: Validate tháng bắt buộc

<!DOCTYPE html>
<html>
<head>
    <style>
        html, body { height: 100%; margin: 0; font-family: sans-serif; }
        body {
            text-align: center; color: white;
            background: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%) center/cover no-repeat;
        }
        input[type="month"] {
            display: block; width: 35%; margin: 15px auto;
            border: 2px solid white; background: transparent;
            color: white; font-weight: bold; padding: 8px;
        }
        .btn {
            background: #0197F6; border: none; color: white;
            padding: 10px 20px; border-radius: 4px; width: 35%;
            margin: 20px auto; display: block; cursor: pointer;
        }
        .show { font-size: 1.5rem; color: #dc3545; font-weight: bold; margin-top: 15px; }
    </style>
</head>
<body>
    <h1>Demo Input Month required Property</h1>
    <form action="" onsubmit="return checkInput(event)">
        <p>Tháng sinh của bạn?</p>
        <input type="month" class="monthInput" required>
        <input type="submit" value="Gửi">
    </form>
    <div id="result" class="show"></div>
    <script>
        function checkInput(e) {
            var input = document.querySelector(".monthInput");
            if (input.value === '') {
                document.getElementById("result").textContent = "Vui lòng chọn tháng!";
                e.preventDefault(); // Ngăn submit
            }
        }
    </script>
</body>
</html>

Kết quả

Form yêu cầu chọn tháng:

Thuộc tính required của Input Month trong HTML DOM

Nhấn "Gửi" không chọn - trình duyệt chặn và báo lỗi:

Thuộc tính required của Input Month trong HTML DOM

✅ Thực hành:
  • Validation HTML5 chạy tự động trước onsubmit.
  • Có thể tùy chỉnh thông báo: input.setCustomValidity("...").
  • Kết hợp min/max để giới hạn tháng hợp lệ.