Validation in HTML5. :invalid classe after submit

前端 未结 9 2485
清歌不尽
清歌不尽 2021-02-18 14:11

I\'m building a form and I want to use the :invalid selector to give the \"required\" input fields a red border if the user presses submit without filling them, but

相关标签:
9条回答
  • 2021-02-18 14:42

    Very simple just use #ID:invalid:focus

    This only does the validation when focused on and not on page load

    0 讨论(0)
  • 2021-02-18 14:48

    Old question, but for people that might might find it useful: I made a little script that adds a class to a form when it's attempted to be submitted, so that you can style forms that have and haven't been attempted to be submitted differently:

    window.addEventListener('load', function() {
    
        /**
         * Adds a class `_submit-attempted` to a form when it's attempted to be
         * submitted.
         *
         * This allows us to style invalid form fields differently for forms that
         * have and haven't been attemted to submit.
         */
        function addFormSubmitAttemptedTriggers() {
    
            var formEls = document.querySelectorAll('form');
    
            for (var i = 0; i < formEls.length; i++) {
    
                function addSubmitAttemptedTrigger(formEl) {
    
                    var submitButtonEl = formEl.querySelector('input[type=submit]');
    
                    if (submitButtonEl) {
                        submitButtonEl.addEventListener('click', function() {
                            formEl.classList.add('_submit-attempted');
                        });
                    }
    
                }
    
                addSubmitAttemptedTrigger(formEls[i]);
    
            }
    
        }
    
        addFormSubmitAttemptedTriggers();
    
    });
    

    Now forms that are attempted to be submitted will get a class _submit-attempted, so you can only give these fields a red box shadow:

    input {
        box-shadow: none;
    }
    
    form._submit-attempted input {
        box-shadow: 0 0 5px #F00;
    }
    
    0 讨论(0)
  • 2021-02-18 14:52

    I tried this in my website:

    <style id="validation"></style>
    <script>
    function verify() {
        document.getElementById("validation").innerHTML = "input:invalid { border: 1px solid red!important;}input:valid { border: 1px solid green;}";
        }
    </script>
    

    Then add onclick="verify()" to your submit button, just like this:

    <input type="submit" onclick="verify()">
    
    0 讨论(0)
提交回复
热议问题