Skip to main content

An example of using CSS and HTML5 pattern attribute for form validation with inline error messages.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Native HTML5 validation with CSS &amp; Regex</title>

<style type="text/css">
  /* When the input is invalid and not blank */
  input:invalid:not(:placeholder-shown) {
    border: 2px solid red !important;
  }

  /* When input is invalid, show and make the adjacanet validation text red */
  input:invalid:not(:placeholder-shown) + [data-validation-text] {
    color: red !important;
    display: block;
  }

  /* Hide validation text by default */
  [data-validation-text] {
    display: none;
  }

  /* Ignore everything below, just to make the demo pretty */
  body,
  html {
    background-color: #f7f7f7;
  }

  * {
    box-sizing: border-box;
  }

  form {
    width: 400px;
    margin: 50px auto 0 auto;
    background-color: #fff;
    padding: 20px;
    border: 1px solid #cecece;
  }

  label {
    display: block;
    margin-top: 15px;
    margin-bottom: 5px;
  }

  input {
    display: block;
    width: 100%;
    padding: 5px;
    border: 1px solid #cecece;
  }

  label {
    font-weight: bold;
    font-size: 12px;
    font-family: sans-serif;
    color: #888;
  }

  span {
    font-family: sans-serif;
    font-size: 12px;
    margin-top: 5px;
  }

  h1 {
    font-size: 18px;
    font-family: sans-serif;
  }
</style>
</head>
<body>

<p>
  An example of using CSS and HTML5 pattern attribute for form validation with
  inline error messages.
</p>

<form>
  <h1>Native form validation with CSS &amp; Regex</h1>

  <label>Name</label>
  <input type="text" pattern=".{5,}">
  <span data-validation-text>Must be 5 chars or more</span>

  <label>Email</label>
  <input type="email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,63}$">
  <span data-validation-text>Must be a valid email</span>

  <label>Phone</label>
  <input type="text" pattern="([0-9]|\s){2,}">
  <span data-validation-text>Must be 2 chars or more, only numbers and spaces allowed</span>
</form>

<p><a href="https://codepen.io/helgesverre/pen/vWRevp">CodePen</a></p>
</body>
</html>