How to require two form fields to match with HTML5 with JavaScript?

Spread the love

Sometimes, we want to require two form fields to match with HTML5 with JavaScript.

In this article, we’ll look at how to require two form fields to match with HTML5 with JavaScript.

How to require two form fields to match with HTML5 with JavaScript?

To require two form fields to match with HTML5 with JavaScript, we set the pattern property of the 2nd input to match the first.

For instance, we write

<form>
  <input
    type="text"
    oninput="form.confirm.pattern = escapeRegExp(this.value)"
  />
  <input name="confirm" pattern="" title="Fields must match" required />
</form>
<script>
  function escapeRegExp(str) {
    return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  }
</script>

to call escapeRegExp with the first input’s value to return a regex string that we set as the pattern attribute value of the 2nd input.

We get the 2nd field with form.confirm, where confirm is the name attribute value.

Conclusion

To require two form fields to match with HTML5 with JavaScript, we set the pattern property of the 2nd input to match the first.

Leave a Reply

Your email address will not be published. Required fields are marked *