-
-
Save jCrip/45da5dca13ed5f43872699c17ec22eef to your computer and use it in GitHub Desktop.
HTML5 Form Validation Fallback (without a library)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); | |
} | |
}); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.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