http://www.alistapart.com/articles/forward-thinking-form-validation/
Omdat we alleen willen aangeven dat een veld ongeldig is zodra het veld ongeldig is
focus, gebruiken we de focus pseudo-klasse om de ongeldige stijl te activeren.
(Uiteraard worden alle verplichte velden vanaf het begin als ongeldig gemarkeerd
zou een slechte ontwerpkeuze zijn.)
Als u deze logica volgt, ziet uw code er ongeveer zo uit ...
<script>
document.addEventListener('DOMContentLoaded', function() {
var required = document.querySelectorAll('input:required');
for (var i = 0; i < required.length; ++i) {
(function(elem) {
function removeClass(name) {
if (elem.classList) elem.classList.remove(name);
else
elem.className = elem.className.replace(
RegExp('(^|\\s)\\s*' + name + '(?:\\s+|$)'),
function (match, leading) {return leading;}
);
}
function addClass(name) {
removeClass(name);
if (elem.classList) elem.classList.add(name);
else elem.className += ' ' + name;
}
//If you require a class, and you use JS to add it, you end up
//not showing pink at all if JS is disabled.
//One workaround is to have the class on all your elements anyway,
//and remove it when you set up proper validation.
//The main problem with that is that without JS, you see what you're
//already seeing, and stuff looks hideous.
//Unfortunately, you kinda have to pick one or the other.
//Let non-blank elements stay "touched", if they are already,
//so other stuff can make the element :invalid if need be
if (elem.value == '') addClass('touched');
elem.addEventListener('blur', function() {
addClass('touched');
});
//Oh, and when the form submits, they need to know about everything
if (elem.form) {
elem.form.addEventListener('submit', function() {
addClass('touched');
});
};
})(required[i]);
}
});
</script>
En natuurlijk werkt het niet zoals in IE8 of lager, omdat (a) DOMContentLoaded
relatief nieuw is en niet standaard was toen IE8 uitkwam, (b) IE8 gebruikt attachEvent
in plaats van de DOM-standaard addEventListener
, en (c) IE8 zal sowieso niet om : required
geven, omdat het HTML technisch niet ondersteunt 5.