http://www.alistapart.com/articles/forward-thinking-form-validation/
Sadece bir alanın sahip olduğu zaman bir alanın geçersiz olduğunu belirtmek istediğimizden
Odaklama, geçersiz stil tetiklemek için odak sözde sınıfı kullanıyoruz.
(Doğal olarak, gerekli tüm alanları başlangıçtan itibaren geçersiz olarak işaretleme
kötü tasarım tercihi olurdu.)
Bu mantığı takiben, kodun böyle bir şey görecekti ...
<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>
Ve tabii ki, IE8'de olduğu gibi (a) DOMContentLoaded
nispeten yeni ve IE8 çıktığında standart değildi, (b) IE8 attachEvent kullanıyor HTML'yi teknik olarak desteklemediği için DOM standardı addEventListener
yerine
ve (c) IE8, : required
ile ilgilenmeyecektir. 5.