DEV Community

Ibrahim
Ibrahim

Posted on

Validating File Size in a File Input Using JavaScript

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>
Enter fullscreen mode Exit fullscreen mode

First, listen for changes when the user selects a file from the input.

const inputFile = document.querySelector('input[type=file]');

inputFile.addEventListener('change', e => {
  //
});
Enter fullscreen mode Exit fullscreen mode

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
  }
});
Enter fullscreen mode Exit fullscreen mode

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];
  }
});
Enter fullscreen mode Exit fullscreen mode

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
    }
  }
});
Enter fullscreen mode Exit fullscreen mode

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('');
  }
});
Enter fullscreen mode Exit fullscreen mode

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:

File Input Size Validation Error

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');
    }
  }
});
Enter fullscreen mode Exit fullscreen mode

Here's the result:

File Input Size Validation Alert

Top comments (0)