[JavaScript] Check the validity of a form before its submission

Published on 2019-06-17 • Modified on 2020-04-20

It's now common to have forms using multiple steps. Generally you build one form and depending on the current step you will display some of its fields. Therefore, if you have a "Next step" button, it will not trigger the submit button and the HTML5 client validation will not be done. This can be problematic in the last step when you hit the submit button but some fields of the previous steps are not valid. The validation will be triggered, but as the fields of the previous steps are not currently displayed, the user will not see the errors and will not understand why he is blocked at the last step. So, this function will allow us to check that the form is valid before going to the next step. We can force the submit because we know the form is not valid, therefore it will force the display of the current step's errors to the user.
[Edit 2020-04-20] Added a real Vue.js demo.


/**
 * I am using a JavaScript module to isolate the code of each snippet.
 * In fact it's a Vue.js mixin. Take the code called by the mounted()
 * or the snippetXX() function.
 */
export default {
  data: {
    snippetFeedback: ''
  },
  methods: {
    snippet28: function () {
      if (!this.$refs.myForm.checkValidity()) {
        this.$refs.myFormSubmit.click()
        this.snippetFeedback = 'Form is NOT valid. Enter a value.'
      } else {
        this.snippetFeedback = 'Form is valid.'
      }
      // That's it! 😁
    }
  }
}
HTML demo of the snippet

» ≪ snippetFeedback ≫


 More on Stackoverflow   Read the doc  Random snippet

  Work with me!