Sometimes, we want to validate a file upload field using JavaScript.
In this article, we’ll look at how to validate a file upload field using JavaScript.
How to validate a file upload field using JavaScript?
To validate a file upload field using JavaScript, we can check the value
property.
For instance, we write:
<form>
<input type='file'>
<input type='submit'>
</form>
to add a form.
Then we write:
const form = document.querySelector('form')
const input = document.querySelector('input[type="file"]')
form.onsubmit = (e) => {
e.preventDefault()
if (input.value) {
console.log('file selected')
}
}
to select the form and the file input with querySelector
.
Then we set the form.onsubmit
property to a function that checks if input.value
is truthy.
If it is, then we know the file input has a selected file.
Conclusion
To validate a file upload field using JavaScript, we can check the value
property.