Conditional form submition with async function

Hi,

I have a form that collect phone numbers and part of the validation is to make an async call to AbstractAPI which valid the phone for us. When the phone number is correct te form should be submited normaly, when not we show a message and the form should not be formated.

I have tried to attached the function on form.submit event, but the form still gets submitted, so I moved it too the button and now forms.submit() doesn’t work.

I have tried a custom button, but the form doesn’t submit or the UI shows an error “Oups something went wrong”. Apparently Webform needs a submit button.

So how can I attach a function on my form, that check the data async and block the submittion until I trigger it myself?

I embed this code in a ‘embeded cod’ block in my form:

document.addEventListener(“DOMContentLoaded”, function () {
const form = document.getElementById(‘email-form’);
const phoneInput = document.getElementById(‘phone’);

form.addEventListener('submit', async function (event) {
  event.preventDefault(); // Stop the form from submitting immediately
  const phoneNumber = phoneInput.value;
  const response = await fetch(`https://phonevalidation.abstractapi.com/v1/?api_key=${apiKey}&phone=${encodeURIComponent(fullPhone)}`);
  const data = await response.json();

  if (data.valid) {
    form.submit();
  } else {
    alert("Invalid phone number. Please check and try again.");
  }
});

});

You have a few ways, but probably the easiest approach for you is;

Init form;

  • Force the phone number field to be required, and invalid, e.g. some kind of obtuse pattern it will never match, or a maxlength of 0, which can’t happen on a required field.

On exit from the phone input field

  • Any change re-invalidates that field, e.g. maxlength = 0
  • Trigger your async phone validation on phone input blur, meaning when the user leaves that field. If the function returns success, remove your maxlength constraint. If it fails, display your error message next to the field

This way the form can only be submitted if [1] the phone has been entered and [2] it passed validation. You don’t need to do anything with form submit.