HTML pattern Attribute

HTML pattern Attribute: This attribute defines a regular expression that the <input> element value is checked against. And the pattern attribute works with the following input types: text, date, search, url, tel, email, and password.



HTML pattern Attribute

This attribute can be applied to <input> element.

Syntax: <input pattern=”regexp”>

Browser Support

This attribute is supported by the following browsers:

  • Chrome-5.0
  • Firefox-4.0
  • Internet Explorer-10.0
  • Safari-does not support
  • Opera-9.6

Example: for <input> element that contain only 3 letters.

<!DOCTYPE html>
<html>
<body>
<form action="/action_page.php">
  Country code: <input type="text" name="country_code" pattern="[A-Za-z]{3}" title="Three letter country code">
  <input type="submit">
</form>
</body>
</html>

Output:

html pattern attribute

Example: for <input> element with type =”password” it must contain 6 or more characters

<!DOCTYPE html>
<html>
<body>
<form action="/action_page.php">
  Password: <input type="password" name="pw" pattern=".{6,}" title="Six or more characters">
  <input type="submit">
</form>
</body>
</html>

Output:

html pattern attribute

Example: for <input> element with type=”password” it must contain 8 or more characters that are of at least one number, uppercase, and lowercase letter.

<!DOCTYPE html>
<html>
<body>
<form action="/action_page.php">
Password: <input type="password" name="pw" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" title="Must contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters">
<input type="submit">
</form>
</body>
</html>

Output:

HTML password element