Thuộc tính required của <input type="file"> 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 tệp trước khi submit form.
Cú pháp
Lấy giá trị:
fileInput.required
Thiết lập giá trị:
fileInput.required = true | false
Ví dụ: Validate file bắt buộc
<!DOCTYPE html>
<html>
<head>
<style>
body { text-align: center; font-family: sans-serif; padding: 20px; }
form { margin: 20px auto; max-width: 400px; }
fieldset { border: 1px solid #ddd; border-radius: 5px; padding: 15px; }
legend { font-weight: bold; }
.btn {
display: block; margin: 15px auto;
background-color: #dc3545; color: white; border: 1px solid #dc3545;
padding: 10px; border-radius: 25px; width: 50%;
font-weight: bold; cursor: pointer;
}
.msg { font-weight: bold; font-size: 1.2rem; color: #ffc107; margin-top: 15px; }
</style>
</head>
<body>
<h1>Ví dụ FileUpload required</h1>
<form id="myForm" method="post">
<fieldset>
<legend>Form Upload</legend>
<input type="file" id="fileInput" required>
<br><br>
<input type="submit" class="btn" value="Gửi Form" onclick="event.preventDefault(); checkRequired()">
</fieldset>
</form>
<div id="msg" class="msg"></div>
<script>
function checkRequired() {
var fileBtn = document.getElementById("fileInput");
var msg = document.getElementById("msg");
if (fileBtn.value === "") {
msg.textContent = "Vui lòng chọn một tệp!";
msg.style.color = "#dc3545";
} else {
msg.textContent = "Đã chọn: " + fileBtn.files[0].name;
msg.style.color = "#28a745";
}
}
</script>
</body>
</html>
Kết quả
Form ban đầu:

Nhấn "Gửi Form" không chọn file - trình duyệt hiển thị validation mặc định:

✅ Lưu ý:
- Validation
requiredchạy **trước** sự kiệnonsubmit. - Nên kết hợp kiểm tra
fileInput.files.length > 0trong JS để xử lý tùy chỉnh. - Thuộc tính
requiredtrên file input chỉ kiểm tra có chọn file, **không** kiểm tra loại/dung lượng file.