File size validation can be handled on the client side using JavaScript.
For example, the following form contains a file input:
<form>
  <label for="image">Select Image</label>
  <input type="file" id="image" />
  <button>Upload</button>
</form>
First, listen for changes when the user selects a file from the input.
const inputFile = document.querySelector('input[type=file]');
inputFile.addEventListener('change', e => {
  //
});
Inside the listener, check whether a file has been selected:
const inputFile = document.querySelector('input[type=file]');
inputFile.addEventListener('change', e => {
  if (e.target.files.length) {
    // Validate
  }
});
If any file is selected, retrieve it:
const inputFile = document.querySelector('input[type=file]');
inputFile.addEventListener('change', e => {
  if (e.target.files.length) {
    const file = e.target.files[0];
  }
});
Get the file size using the size property. The file size is in bytes.
Add a variable to set the maximum file size. Then, compare the variable with the file size.
const inputFile = document.querySelector('input[type=file]');
inputFile.addEventListener('change', e => {
  if (e.target.files.length) {
    const file = e.target.files[0];
    const maxFileSize = 1000 * 1000 * 5; // 5MB
    if (file.size > maxFileSize) {
      // Error
    }
  }
});
If the file size is too large, set a validation error on the input or show an alert.
Example using input validation:
const inputFile = document.querySelector('input[type=file]');
inputFile.addEventListener('change', e => {
  if (e.target.files.length) {
    const file = e.target.files[0];
    const maxFileSize = 1000 * 1000 * 5; // 5MB
    if (file.size > maxFileSize) {
      inputFile.setCustomValidity(
        'The selected file must not be larger than 5MB'
      );
      inputFile.reportValidity();
    } else {
      inputFile.setCustomValidity('');
    }
  } else {
    inputFile.setCustomValidity('');
  }
});
Read more about adding validation errors to input elements at https://developer.mozilla.org/en-US/docs/Web/HTML/Guides/Constraint_validation
Here's the result:
Example using alert:
const inputFile = document.querySelector('input[type=file]');
inputFile.addEventListener('change', e => {
  if (e.target.files.length) {
    const file = e.target.files[0];
    const maxFileSize = 1000 * 1000 * 5; // 5MB
    if (file.size > maxFileSize) {
      alert('The selected file must not be larger than 5MB');
    }
  }
});
Here's the result:


    
Top comments (0)