Delay HTML5 :invalid pseudo-class until the first event

前端 未结 13 2069
旧巷少年郎
旧巷少年郎 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 05:01

    While using HTML5 form validation, try to use the browser to detect for invalid submissions/fields, rather than re-inventing the wheel.

    Listen for the invalid event to add a class of 'invalid' to your form. With the 'invalid' class added, you can go to town with styling your form using CSS3 :pseudo selectors.

    For example:

    // where myformid is the ID of your form
    var myForm = document.forms.myformid;
    
    var checkCustomValidity = function(field, msg) {
        if('setCustomValidity' in field) {
            field.setCustomValidity(msg);
        } else {
            field.validationMessage = msg;
        }
    };
    
    var validateForm = function() {
    
        // here, we're testing the field with an ID of 'name'
        checkCustomValidity(myForm.name, '');
    
        if(myForm.name.value.length < 4) {
            checkCustomValidity(
                // alerts fields error message response
                myForm.name, 'Please enter a valid Full Name, here.'
            );
        }
    };
    
    /* here, we are handling your question above, by adding an invalid
       class to the form if it returns invalid.  Below, you'll notice
       our attached listener for a form state of invalid */
    var styleInvalidForm = function() {
        myForm.className = myForm.className += ' invalid';
    }
    
    myForm.addEventListener('input', validateForm, false);
    myForm.addEventListener('keyup', validateForm, false);
    myForm.addEventListener('invalid', styleInvalidForm, true);
    

    Now, simply style your form as you see fit based on the 'invalid' class we've attached.

    For example:

    form.invalid input:invalid,
    form.invalid textarea:invalid {
        background: rgba(255, 0, 0, .05);
        border-color: #ff6d6d;
        -webkit-box-shadow: 0 0 6px rgba(255, 0, 0, .35);
        box-shadow: 0 0 6px rgba(255, 0, 0, .35);
    }
    

提交回复
热议问题