简体   繁体   中英

Display Bootstrap Form Validation Near Submit Button

I have a form which has 40 some questions on it, some required, some optional. At the end when the uses clicks "submit" I'm using Bootstrap's form-validation.js to check things before the form is submitted. This all works fine.

However, the form is so long, when a user hit "submit" all they see are a bunch of green checkmarks on the bottom optional questions. (The only indication they have that the form didn't submit is the page doesn't reload.)

What's the best/easiest/cleanest way to notify users that elements off screen are not meeting validation requirements? (And that the form did not actually submit.)

Javascript is not my strong suite, but my first thought was to modify the form-validation script to make a small div near the submit button visible when an error was found, but I haven't been able to figure out how to make that work. (Could it be as simple as adding a line or two to the form-validation.js?)

// Example starter JavaScript for disabling form submissions if there are invalid fields
(function () {
  'use strict'

  window.addEventListener('load', function () {
    // Fetch all the forms we want to apply custom Bootstrap validation styles to
    var forms = document.getElementsByClassName('needs-validation')
    // Loop over them and prevent submission
    Array.prototype.filter.call(forms, function (form) {
      form.addEventListener('submit', function (event) {
        if (form.checkValidity() === false) {
          event.preventDefault()
          event.stopPropagation()
        }
      }, false)                         
    })
  }, false)

}()) 

Got a suggestion on Twitter to just use the CSS Psuedo class that gets applied to an invalid form:

Twitter Suggestion :

Chimin' in from the peanut gallery here: the :invalid pseudo-class will be set on a form element if any input inside of it is invalid. You could do something like form:invalid > input[type=submit]:after { /* Your message */ }

Couldn't get the text to appear, but ended up adding some css to to grey out the button if form is invalid. Works like a charm.

            form:invalid > input[type=submit]{background-color:#ccc;}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM