It's my first post here and please pardon me for my english. Here's the problem i've encountered: I am trying to validate user's address when submitting a form using an external API. My goal is to prevent form from submitting based of an asynchronously defined variable (which is the error). I would like to somehow return a variable from an async function (variable is redefined after a promise-based request to the API). Here is the code:
function validateAdress(requestString) {
callToTheAPIMethod(request).then((res) => {
let error;
const obj = res.getDataFromApi ...obj data from async call
const precision = ...parameters from an API on which i rely in order to set up the error message
if (obj) {
switch (precision) {
case "exact":
error = "";
break;
case "number":
case "near":
case "range":
error = "Adress is incorrect. Please specify house number";
break;
case "street":
error = "Adress is incorrect. Please specify house number";
break;
case "other":
default:
error = "dress is incorrect. Please specify smth...";
}
}
$(".address_error").text(error);
return error;
});
}
function validateForm() {
validateAdress(requestString)
if (validateAdress(requestString) return false
///i get it that i am not able to return the variable directly from this call, only a promise to resolve
/// if error is not empty prevent form from submitting
...some other code validating input fields
}
As a result the error variable gets assigned with a text string specifying type of an error and it is added to the DOM. validateAdress function is called in some other function which is used to validate a form on a client-side. The problem is that i am trying to prevent the form from submitting if the variable error has been assigned with a value. It seems to me that it is not possible to do so. If i am trying to return that variable from validateAdress functions it is obviously returning undefined... Unfortunately, i am also not able to use async/await syntax here.. I would highly appreciate if someone can give me a hint how to implement that sort of functionaly or how to access the error variable.
You can call preventDefault on the form submit handler, call the async function, if everything is OK, call the forms submit method.
eg..
const form = document.querySelector('form');
const input = document.querySelector('input');
function check(done) {
setTimeout(() => {
done(input.value === '1');
}, 1000);
}
form.addEventListener('submit', e => {
e.preventDefault();
check(ok => {
if (ok) form.submit();
else console.log('try again.');
});
});
Type 1 into input and press enter, and wait 1 second..
<form>
<input />
</form>