A Simple HTML5 Form Validation
by kpowz
HTML
<h1>A Simple HTML5 Form Validation</h1>
<p>Leave the field empty, with leading or trailing space and submit the form to see what happens.</p>
<form>
<label for="name">* Name</label>
<input type="text" id="name" required pattern="^(?! )[A-Za-z0-9 ]*(?<! )$">
<button type="submit" value="Submit">Submit</button>
</form>
<footer>Which browsers support this feature? - <a href=http://caniuse.com/form-validation>Caniuse.com</a></footer>https://jsfiddle.net/kpowz/6f1sebzh/#fork
CSS
body {
margin: 1em;
}
footer {
margin-top: 2em;
}
JavaScript
const form = document.getElementsByTagName('form')[0];
const submitButton = document.getElementsByTagName('button')[0];
// this would actual hook - validity (enable disable)
submitButton.addEventListener('click', function (event) {
// if the email field is valid, we let the form submit
console.log('found button click')
var isValidForm = form.checkValidity();
alert(isValidForm);
console.log(isValidForm)
});
// this would actually be the other hook (submittal)
form.addEventListener('submit', function (event) {
// if the email field is valid, we let the form submit
console.log('found form')
var isValidForm = form.checkValidity();
alert(isValidForm);
console.log(isValidForm)
});