Shopify Theme: Sync Validation Function

New Member
8 0 0

So I'm using the Debut theme which appears to have an input field of type submit styled to look like a button:

                <input type="submit" name="checkout"
                  class="cart__submit btn btn--small-wide"
                  value="{{ 'cart.general.checkout' | t }}">

Basically, I want to prevent the submission based on a validation function. Should the validation return false I want to redirect to another page much like a 404 error. If the validation returns true, I instead want to continue the checkout flow as per usual. I've added a custom onsubmit handler like so to the form that wraps this button in the cart-template.liquid file like so:

<form action="{{ routes.cart_url }}" method="post" novalidate class="cart" onsubmit="return redir(event)">

Now the only concern at this point is the validation which is based on a remote API. I have the following function which I've defined and included in an asset script called redir.js.liquid:

function redir(event) {
  fetch("https://remoteapi.com/example")
    .then(resp => resp.json())
    .then(data => {
    	// check data here, return T/F
    });
  return false;
}

Now the problem is that fetch is a promise (i.e. async) and thus regardless of what I do in the then clause (I've tried event.preventDefault() if false) the form submission will still execute before it resolves. That being said, how do I synchronously execute a remote API call to pause the form submission, do some validation on the data, and then determine whether or not to submit/redirect?

0 Likes