HTML5 Constraint Validation Example

HTML

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<form class="form-inline" id="frm" method="post">
  <div class="form-group">
    <input type="text" id="txtCC" placeholder="Country Code" pattern="[A-Za-z]{3}" title="Three letter country code" class="form-control">
  </div>
  <br />
  <br />
  <div class="form-group">
    <input type="email" id="txtEmail1" required class="form-control" placeholder="Email">
  </div>
  <br />
  <br />
  <div class="form-group">
    <input type="email" id="txtEmail2" required class="form-control" placeholder="Confirm Email">
  </div>
  <br />
  <br />
  <div class="form-group">
    <input type="text" id="txtLength" placeholder="Test Length" maxlength="12" value="0123456789013あ" title="Three letter country code" class="form-control">
  </div>
  <br/>
  <br/>
  <input type="submit" value="Submit" class="btn btn-primary" id="btnSubmit" />



<!--

set a green validation message to the side of the button 
make it fade out after 6 seconds.

-->

JavaScript

$("#txtEmail1").on("input", function() {
  var email1 = $(this);
  var email2 = $("#txtEmail2");
  emailComparer(email1, email2);
});

$("#txtEmail2").on("input", function() {
  var email1 = $("#txtEmail1");
  var email2 = $(this);
  emailComparer(email1, email2);
});

function emailComparer(email1, email2) {
  if (email2.val() != "") {
    if (email1.val() != "") {
      if (email1.val() != email2.val()) {
        email2[0].setCustomValidity("Email values do not match");
        return;
      }
    }
  }
  email2[0].setCustomValidity("");

}

$("#btnSubmit").click(function(e) {

  // $("#tbl")[0].setCustomValidity("You ugly!");
  //You cannot set a message for non-form elements b/c they don't have a "setCustomValidity" function.

  var frm = $("#frm");

  var formValid = frm.get(0).checkValidity();
  if (formValid) {
    alert("HOORAY");
    e.preventDefault();
    //send ajax
  }
});