Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> HTML

HTML DOM Input FileUpload required Property: บังคับเลือกไฟล์

คุณสมบัติ required ของ file upload คืนค่าและกำหนดว่าช่องอัปโหลดบังคับต้องเลือกไฟล์ก่อนส่งฟอร์มหรือไม่

รูปแบบ (Syntax)

อ่านค่า:

object.required

กำหนดค่า:

object.required = true | false

ตัวอย่างการใช้งาน

ฟอร์มที่บังคับให้เลือกไฟล์ก่อนส่ง:

<!DOCTYPE html>
<html>
<head>
    <style>
        body { text-align: center; }
        .btn { display: block; margin: 1rem auto; background-color: #db133a; color: #fff; border: 1px solid #db133a; padding: 0.5rem; border-radius: 50px; width: 20%; }
        .show-message { font-weight: bold; font-size: 1.4rem; color: #ffc107; }
    </style>
</head>
<body>
    <h1>ตัวอย่าง file upload required Property</h1>
    <form id="form" method="post" action="">
        <fieldset>
            <legend>Form</legend>
            <input type="file" required>
            <input type="submit" class="btn" value="ส่งฟอร์ม" onclick="checkRequired()">
        </fieldset>
    </form>
    <div class="show-message"></div>
    <script>
        function checkRequired() {
            var fileBtn = document.querySelector("input[type='file']");
            if (fileBtn.value === "") {
                document.querySelector(".show-message").innerHTML = "กรุณาเลือกไฟล์!";
            }
        }
    </script>
</body>
</html>

พฤติกรรมของเบราว์เซอร์

  • เบราว์เซอร์จะบล็อกการส่งฟอร์มและแสดงข้อความแจ้งเตือนอัตโนมัติ
  • ข้อความแจ้งเตือนขึ้นอยู่กับเบราว์เซอร์และภาษาที่ตั้งค่า
  • สามารถปรับแต่งข้อความได้ด้วย setCustomValidity()

การปรับแต่งข้อความแจ้งเตือน

var fileInput = document.querySelector("input[type='file']");
fileInput.addEventListener("invalid", function() {
    if (this.validity.valueMissing) {
        this.setCustomValidity("กรุณาเลือกไฟล์ก่อนส่งฟอร์ม");
    }
});
fileInput.addEventListener("change", function() {
    this.setCustomValidity(""); // ล้างข้อความเมื่อเลือกไฟล์แล้ว
});