-
The file upload control in Basic Forms (especially when using Attachment or File columns) is rendered by Power Pages using iframes or Shadow DOM, or is deeply nested in dynamically generated markup.
-
Standard document.querySelector('input[type=file]') may not find it.
-
You may also run into timing issues: the control may not be rendered when your script runs.
Step-by-step approach:
1. Add your custom file input (optional but easier)
Instead of using the out-of-the-box Attachment field, use a custom HTML file input in your Basic Form Web Page:
Place this in the Custom HTML (Web File or inside the form).
2. Add JS for validation
This example checks for Excel files with a column "Email" and at least 2 rows:
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
const fileInput = document.getElementById("customFileUpload");
const errorMsg = document.getElementById("fileErrorMsg");
let fileIsValid = false;
fileInput.addEventListener("change", function (e) {
const file = e.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = function (evt) {
const data = evt.target.result;
const workbook = XLSX.read(data, { type: "binary" });
const sheetName = workbook.SheetNames[0];
const sheet = workbook.Sheets[sheetName];
const json = XLSX.utils.sheet_to_json(sheet, { header: 1 });
const headerRow = json[0];
if (!headerRow.includes("Email")) {
errorMsg.textContent = "Missing required column: Email";
fileIsValid = false;
return;
}
if (json.length < 2) {
errorMsg.textContent = "File must contain at least 1 data row.";
fileIsValid = false;
return;
}
errorMsg.textContent = "";
fileIsValid = true;
};
reader.readAsBinaryString(file);
});
document.querySelector("form").addEventListener("submit", function (e) {
if (!fileIsValid) {
e.preventDefault();
errorMsg.textContent = "Please upload a valid file before submitting.";
}
});
});
</script>
3. Hiding the default attachment control
You can hide the default file upload control rendered by Power Pages:
div[data-name='your_field_schema_name'] {
display: none !important;
}
This allows you to use your own custom control and logic instead.
4. (Optional) Storing the file in Dataverse
If you're bypassing the built-in file upload field, and still want to store the uploaded file in Dataverse, you'll need to: