custom form validators

by Soviut

HTML

<form>
  <label>
    Full Name
    <input type="text" name="full_name" required>   
  </label>

  <label>
    Phone number
    <input type="tel" name="phone" required pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" title="Format must be 555-555-5555">
  </label>

  <label>
    Must Match
    <input type="text" id="match_first" required>
    <input type="text" id="match_second" required>
  </label>
  
  <button type="submit">Submit</button>
</form>

<br/>
<br/>

<a href="https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation#Constraint_API%27s_element.setCustomValidity()">learn more</a>

CSS

body {
  font-family: arial, helvetica, san-serif;
}

label {
  display: block;
  margin-bottom: 0.5em;
}

label > input {
  display: block;
  margin-bottom: 0.3em;
  padding: 0.5em;

  border: solid 1px #CCC;
  border-radius: 3px;
  font-size: 1em;
}

button {
  padding: 0.5em 1em;
  
  background: #336699;
  color: #FFF;
  border: 0;
  border-radius: 3px;
  font-size: 1em;
}

JavaScript

let matchFirst  = document.getElementById('match_first')
let matchSecond = document.getElementById('match_second')

function validate(e) {
  matchSecond.setCustomValidity( (matchFirst.value !== matchSecond.value) ? 'both fields must match' : '' )
}

matchFirst.addEventListener('input', validate)
matchSecond.addEventListener('input', validate)