Categories
HTML Tutorials

Ensuring a value is within bounds

You use the min and max attributes to ensure that numeric and date values are within a specific range.

Using the min and max attributes
<html>
  <head>
    <title>Example</title>
    <meta name="author" content="Adam Freeman"/>
    <meta name="description" content="A simple example"/>
    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
  </head>
  <body>
    <form method="post" action="http://titan:8080/form">
      <input type="hidden" name="recordID" value="1234"/>
      <p>
        <label for="name">
          Name:
          <input type="text" id="name" name="name"/>
        </label>
      </p>
      <p>
        <label for="password">
          Password: <input type="password" placeholder="Min 6 characters" id="password" name="password"/>
        </label>
      </p>
      <p>
        <label for="price">
          $ per unit in your area:
          <input type="number" min="0" max="100" value="1" id="price" name="price"/>
        </label>
      </p>
      <input type="submit" value="Submit"/>
    </form>
  </body>
</html>

You need not apply both attributes. You create an upper limit for the value if you apply just the max attribute, and a lower limit if you apply just the min attribute. When you apply both, you constrain the upper and lower values to create a range. The min and max values are inclusive, meaning that if you specify a max value of 100, then any value up to and including 100 is allowed. You can see how the browser reports a range validation error below.