Gecikish HTML5: birinchi voqea qadar noto'g'ri pseudo-sinf

Yaqinda sahifani yuklamasdanoq : invalid pseudo-class zarur formalaridagi elementlarga nisbatan qo'llanilishini aniqladim. Misol uchun, agar sizda ushbu kod mavjud bo'lsa:


…
<input name="foo" required />

So'ngra sahifangizda bo'sh pushti kirish elementi bilan yuklanadi. HTML5-ga o'rnatilgan tasdiqlash katta bo'lsa-da, lekin ko'pchilik foydalanuvchilar bu shaklni hech qanday qadriyatlarni kiritish imkoniga ega bo'lmagani uchun tasdiqlashlarini kutishmaydi. Birinchi element ushbu elementga ta'sir qilmaguncha, pseudo-sinfni qo'llashni kechiktirishning biron bir usuli mavjudmi? (Ariza yuborish, loyqalash, o'zgartirish, nima bo'lishidan qat'iy nazar)? Buni JavaScript-ni bajarish mumkinmi?

48
Men izoh berishga qodir emasman, shuning uchun @ user3284463 uchun ushbu qo'shimchani qo'shaman. makeDirty iflos sinfni almashtirmasligi kerak, uni kelajakda (ko'k, bekor, amalda) saqlab turish kerak makeDirty (e ) {if (! e.target.classList.contains ('iflos')) e.target.classList.add ('iflos'); }
qo'shib qo'ydi muallif Abir Stolov, manba

9 javoblar

http://www.alistapart.com/articles/forward-thinking-form-validation/

Faqat bizda faqat bitta maydon bekor bo'lganligini bildirmoqchimiz   diqqat markazida biz noto'g'ri uslubni tetiklash uchun mavzu pseudo-sinfidan foydalanamiz.   (Tabiiyki, barcha kerakli maydonlarni boshidan e'tiboran bekor deb belgilash   kambag'al dizayn tanlovi bo'ladi.)

Ushbu mantiqdan so'ng sizning kodingiz shu kabi narsalarga o'xshaydi ...


<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>

Va, albatta, u IE8da yoki undan pastda ishlamaydi, chunki (a) DOMContentLoaded nisbatan yangi va IE8 chiqqanda standart bo'lmagan, (b) IE8 attachEvent addEventListener o'rniga va (c) IE8 texnik jihatdan HTML-ni qo'llab-quvvatlamasa ham, : required haqida g'amxo'rlik qilmaydi. 5.

1
qo'shib qo'ydi

I created a small shim to deal with this in my codebase. I just start off with my <form/> element having the novalidate property along with a data-validate-on="blur" attribute. This watches for the first event of that type. This way you can still use the native :invalid CSS selectors for the form styling.

$(function() {
    $('[data-validate-on]').each(function() {
        var $form = $(this);
        var event_name = $form.data('validate-on');

        $form.one(event_name, ':input', function (event) {
            $form.removeAttr('novalidate');
        });
    });
});
1
qo'shib qo'ydi

Yaxshi yo'l CSS kodlari bilan : invalid,: valid va so'ngra ba'zi bir JavaScript-ni kiritish maydonining diqqat-e'tibori tekshirilganligini tekshirish.

CSS:

input.dirty:invalid{ color: red; }
input.dirty:valid{ color: green; }

JS:

// Function to add class to target element
function makeDirty(e){
  e.target.classList.toggle('dirty');
}

// get form inputs
var inputs = document.forms[0].elements;

// bind events to all inputs
for(let input of inputs){
  input.addEventListener('invalid', makeDirty);
  input.addEventListener('blur', makeDirty);
  input.addEventListener('valid', makeDirty);
}

DEMO

0
qo'shib qo'ydi