How to Use the HTML accept Attribute

Usage of the HTML accept attribute

The HTML accept attribute is quite useful as it specifies what file types the user is allowed to choose from the file input box. It helps to narrow down the results for users so that they can get exactly what they need.

The accept attribute can be used only with <input type="file">. It has the following syntax:

<input accept="file_extension|audio/*|video/*|image/*|media_type">

Now, let’s see an example, where we show how you can use the accept attribute to allow image, video and audio files, separately.

Example of using the HTML accept attribute:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      h1 {
        font-size: 18px;
        margin: 20px 0;
      }
      h1 ~ h2 {
        border-top: 1px solid #666;
        padding-top: 20px;
      }
    </style>
  </head>
  <body>
    <form action="/form/submit" method="post">
      <h1>Match all image files</h1>
      <div>
        <label>image/*
          <input type="file" accept="image/*">
        </label>
      </div>
      <h2>Match all video files</h2>
      <div>
        <label>video/*
          <input type="file" accept="video/*">
        </label>
      </div>
      <h2>Match all audio files </h2>
      <div>
        <label>audio/*
          <input type="file" accept="audio/*">
        </label>
      </div>
      <h2>Match all image and video files</h2>
      <div>
        <label>image/*,video/*
          <input type="file" accept="image/*,video/*">
        </label>
      </div>
    </form>
  </body>
</html>

If you need to define more than one value, separate the values with a comma.

Example of using the HTML accept attribute with comma-separated values:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      label {
        display: block;
        margin-bottom: 10px;
        color: #666666;
      }
      input[type="submit"] {
        display: block;
        margin-top: 20px;
        border: 1px solid lightblue;
        background-color: lightblue;
        padding: 5px 10px;
        color: #ffffff;
        cursor: pointer;
      }
      input[type="submit"]:hover {
        background-color: #0b7a9e;
      }
    </style>
  </head>
  <body>
    <form action="/form/submit" method="post">
      <label for="picture">Choose a picture:</label>
      <input type="file" id="picture" name="picture" accept="image/png, image/jpeg">
      <input type="submit" value="Submit">
    </form>
  </body>
</html>
Do not use the accept attribute as a validation tool. File uploads must be validated on the server.