admin管理员组

文章数量:1122846

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,

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,

Share Improve this question asked Jul 30, 2024 at 5:21 ajluxlajluxl 12 bronze badges 2
  • You'll have to inquire with Elementor as they're the ones who know what their form is doing. – Tony Djukic Commented Aug 1, 2024 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, 2024 at 20:02
Add a comment  | 

2 Answers 2

Reset to default 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.

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
  }
}

本文标签: pluginsElementor Formclient side javascript validation