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

Published on 2019-06-17 • Modified on 2019-06-17

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.

    // https://www.w3schools.com/js/js_validation_api.asp (hit the doc button)
    function nextStep() {
        let form = $('#myform');
        if (!form[0].checkValidity()) {
            alert('Please check all fields value before going to the next step.')

            return false;
        // ... go to next step. hide step 1 and display step 2 for example...
    // That's it! 😁