Categories
HTML Tutorials

Ensuring a value is an email address or URL

The email and url types of the input element ensure that the user has entered a valid e-mail address or fully qualified URL, respectively (well, almost—the browser support for the email type is fairly decent, but the url type is somewhat sketchy). We can combine the pattern attribute with these types of input elements to further restrict the values that the user can enter; for example, limiting email address to a particular domain.

Using the pattern attribute with the email input element type
<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" pattern="^.* .*$"/>
        </label>
      </p>
      <p>
        <label for="password">
          Password: <input type="password" placeholder="Min 6 characters" id="password" name="password"/>
        </label>
      </p>
      <p>
        <label for="email">
          Email: <input type="email" placeholder="user@mydomain.com" required pattern=".*@mydomain.com$" id="email" name="email"/>
        </label>
      </p>
      <input type="submit" value="Submit"/>
    </form>
  </body>
</html>

Here, we have used three of the validation features. The email type of the input element ensures that use enters a valid e-mail address. The required attribute ensures that the user provides a value. The pattern attribute ensures that the user enters an e-mail address that belongs to a specific domain (mydomain.com). The use of the email input type and the pattern attribute might seem redundant, but the input element is still responsible for ensuring that everything before the @ character is valid as an e-mail address.