TJ VanToll | @tjvantoll
document.getElementById( "myForm" )
.addEventListener( "submit", function( event ) {
if ( document.getElementById( "myInput" ).value == "" ) {
event.preventDefault();
// Show some questionably UX and a11y
// friendly error message.
}
});
});
<form>
<input required>
<button>Submit</button>
</form>
“No one uses HTML5 form validation”
<form>
<input required type="email">
<button>Submit</button>
</form>
<form>
<input required>
<button>Submit</button>
</form>
curl --data "param1=DELETE * FROM *" http://foo.com/bar.do
<form>
<input required type="email" id="baz">
<button>Go</button>
</form>
<script>
var baz = document.querySelector( "#baz" );
function setErrorMessage() {
if ( baz.validity.valueMissing ) {
baz.setCustomValidity( "Email is required" );
} else if ( baz.validity.typeMismatch ) {
baz.setCustomValidity( "Please provide a valid email address" );
}
};
setErrorMessage();
baz.addEventListener( "change", setErrorMessage );
</script>
<form>
<input required x-moz-errormessage="INVALID!">
<button>Go</button>
</form>
<form>
<input pattern="[0-9]{5}" title="Enter 5 numbers">
<button>Go</button>
</form>
<form id="foo">
<input required>
<button>Go</button>
<script>
document.querySelector( "#foo" )
.addEventListener( "submit", function() {
alert( "hi!" );
});
</script>
</form>
<form>
<input type="text" id="foo" required>
</form>
<style>
#foo:invalid { background: red; }
</style>
Only match after interaction or attempted submission (full algorithm).
<form>
<input type="text" id="bar" required>
<button>Go</button>
</form>
<style>
#bar:-moz-ui-invalid { background: red; }
</style>
WebKit used to have these pseudo-elements.
Chrome 28 removed the pseudo-elements for styling form validation messages.
<form>
<input required id="field-x">
<button>Go</button>
</form>
<script>
document.getElementById( "field-x" )
.addEventListener( "invalid", function( event ) {
event.preventDefault();
});
</script>
<form id="form-x">
<input required>
<button>Go</button>
</form>
<script>
document.getElementById( "form-x" )
.addEventListener( "invalid", function( event ) {
event.preventDefault();
}, true );
</script>
Use code jqchtwcf for 43% off