javascriptformselementor

Elementor Form : client side javascript validation


I already did server side data validation using the hook elementor_pro/forms/validation and it's working fine.

In addition I would like to do client side data validation before submitting the form to fix invalid data straight away avoiding a round trip to the server.

I would like to do custom validation using Javascript and not using the default browser tooltip bubble.

I added this code and the validation works fine, errors messages are displayed on the form. However the form is still submitted when fields input are invalid.

document.addEventListener('submit', (e) => {
  // this is my custom validation function
  validateForm(e);
})

How to prevent the form being submit? preventDefault() function doesn't work as the form submit is done via AJAX.

I would like to know what's the correct way to stop the form submitting when the client side validation failed.


Solution

  • Thanks to your solution Mihai T, I managed to do it : By changing the type of the button to « button », so it won’t submit the form.

    btn.setAttribute("type", "button");
    

    Then adding an listener to the button for click event.

    btn.addEventListener("click", (e) => {
        validateForm(e);
    });
    

    When all inputs (3 in my case : email, tel, text) are correct, set back the type to « submit » for the button.

    function validateForm(e) {
        if (isEmailValid() && isTelValid() && isTextValid()) {
            btn.setAttribute("type", "submit");
        } else {
            //add error messages to UI
        }