Delay HTML5 :invalid pseudo-class until the first event

前端 未结 13 2089
旧巷少年郎
旧巷少年郎 2020-11-30 04:35

I recently discovered that the :invalid pseudo-class applies to required form elements as soon as the page loads. For example, if you have this cod

13条回答
  •  悲哀的现实
    2020-11-30 04:56

    I created a small shim to deal with this in my codebase. I just start off with my

    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');
            });
        });
    });
    

提交回复
热议问题