htm5 form javascript validation
http://www.sitepoint.com/html5-forms-javascript-constraint-validation-api/
1. progressive enhancement: http://jsfiddle.net/trixta/ru7…
http://jsfiddle.net/trixta/ru7jt/
form.checkValidity()
https://html.spec.whatwg.org/multipage/forms.html#dom-form-checkvalidity
https://html.spec.whatwg.org/multipage/forms.html#statically-validate-the-constraints
=====
var form = document.getElementById(“purchaser_form”);
form.noValidate = true;
form.onsubmit = validateForm;
// set handler to validate the form
// onsubmit used for easier cross-browser compatibility
function validateForm(event) {
if (form.checkValidity()) {
return true;
} else {
field = form.querySelector(‘input:invalid, select:invalid, textarea:invalid’);
field.focus();
if (field.checkValidity()) {
removeInvalid(field);
} else {
setInvalid(field);
}
return false;
}
}
function setInvalid(element) {
var message;
var parent = element.parentNode;
if (!parent.classList.contains(‘has-error’)) {
message = document.createElement(‘div’);
message.className = ‘help-block’;
message.innerHTML = element.validationMessage;
parent.classList.add(‘has-error’);
parent.appendChild(message);
} else {
parent.querySelector('.help-block').innerHTML = element.validationMessage;
}
}
function removeInvalid(element) {
var parent = element.parentNode;
if (parent.classList.contains(‘has-error’)) {
parent.classList.remove(‘has-error’);
parent.removeChild(parent.querySelector('.help-block'));
}
}