0

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

Now 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. But 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 to submit ? preventDefault() function doesn't work as the form submit is done via Ajax.

Best regards,

2
  • You'll have to inquire with Elementor as they're the ones who know what their form is doing. Commented Aug 1 at 20:28
  • I asked to Elementor support, they reply they don't provide custom code assistance, this is beyond their scope of support.
    – ajluxl
    Commented Aug 5 at 20:02

2 Answers 2

1

This question isn't really specific to WordPress since it deals with generic JS, but: instead of attaching your validation to the submit action, do it onblur for each field. That way the user gets instant feedback and can be very helpful if they're using keyboard navigation because they only have to tab back one field.

3
  • Thanks for your reply. I'm aware of this possibility but I would like to only show errors the first time when the user click on submit. And then provide live feedback for each field when the user modify his entries. I know how to handle that in js like I did for this form : ajluxl.eu/#contact
    – ajluxl
    Commented Jul 30 at 9:32
  • The problem is that I don't know how to block the default Ajax submission provided by Elementor Form widget when the user click on submit ?
    – ajluxl
    Commented Jul 30 at 9:34
  • Would you mind explaining why you're determined to do this in the least accessible and most user-hostile way you can?
    – Chris Cox
    Commented Jul 30 at 9:58
0

I managed to do it, in short : 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
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.