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

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

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

Cú pháp

Lấy giá trị:

numberInput.required

Thiết lập giá trị:

numberInput.required = true | false

Ví dụ: Validate số 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="number"] {
            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 Number required Property</h1>
    <form action="" onsubmit="return checkInput(event)">
        <p>Ngày sinh của bạn (1-31)?</p>
        <input type="number" class="numberInput" required min="1" max="31">
        <input type="submit" value="Gửi">
    </form>
    <div id="result" class="show"></div>
    <script>
        function checkInput(e) {
            var input = document.querySelector(".numberInput");
            if (input.value === '') {
                document.getElementById("result").textContent = "Vui lòng nhập số!";
                e.preventDefault();
            }
        }
    </script>
</body>
</html>

Kết quả

Form yêu cầu nhập số:

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

Nhấn "Gửi" không nhập - trình duyệt báo lỗi:

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

💡 Mẹo: Kết hợp min, max, step để validate chi tiết hơn (VD: step="0.01" cho giá tiền, min="0" cho số lượng).