JSFiddle - React, Tailwind, and code Playground
by girlie_mac
HTML
<h1>HTML5 Form Validation with pattern matching, with custom error message using ValidityState object</h1>
<p>Username must be alphanumeric and 6 to 12 characters long.</p>
<form>
<label for="username">Username:</label><br/>
<input id="username" type="text" pattern="[a-zA-Z0-9_-]{6,12}" autofocus required title="must be alphanumeric in 6-12 chars">
<input id="submit" type="submit" value="create">
</form>
CSS
/* When the pattern is matched */
input[type=text]:valid {
color: green;
}
/* Unmatched */
input[type=text]:invalid {
color: red;
}
JavaScript
var form = document.forms[0],
submit = document.getElementById('submit'),
input = document.getElementById('username');
input.addEventListener('invalid', function(e) {
if(input.validity.valueMissing){
e.target.setCustomValidity("Please create a username");
} else if(!input.validity.valid) {
e.target.setCustomValidity("This is not a valid username");
}
// to avoid the 'sticky' invlaid problem when resuming typing after getting a custom invalid message
input.addEventListener('input', function(e){
e.target.setCustomValidity('');
});
}, false);