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.");
}
});
});