Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jCrip/45da5dca13ed5f43872699c17ec22eef to your computer and use it in GitHub Desktop.
Save jCrip/45da5dca13ed5f43872699c17ec22eef to your computer and use it in GitHub Desktop.
HTML5 Form Validation Fallback (without a library)
<h1>Cross Browser HTML5 Validation</h1>
<p>Works in the latest version of all browsers. <strong>Note</strong> Codepen iframes may cause issues with validation messages showing.</p>
<form class="validate-form">
<input type="text"
title="required input"
placeholder="required"
required />
<input type="text"
title="Must be 5 numeric numbers"
placeholder="zip code"
pattern="\d{5}"
maxlength="5"
required />
<input type="submit" />
</form>
<p>Status: <span id="status">Unsubmitted</span></p>
function hasHtml5Validation () {
return typeof document.createElement('input').checkValidity === 'function';
}
if (hasHtml5Validation()) {
$('.validate-form').submit(function (e) {
if (!this.checkValidity()) {
e.preventDefault();
$(this).addClass('invalid');
$('#status').html('invalid');
} else {
$(this).addClass('valid');
$('#status').html('submitted');
}
});
}
.invalid input:required:invalid {
background: #BE4C54;
}
.invalid input:required:valid {
background: #17D654 ;
}
input {
display: block;
margin-bottom: 10px;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment