[Help needed] Validation function for add to cart form submission

Zeeshan_Mahmood
Shopify Partner
6 0 3

Hi,

We've added some custom fields into the add to cart form and are trying to add some validation. We've written our custom validation function and are trying to bind it using the following code placed which we placed in theme.liquid within the body tag:

jQuery(function($) {
  $('#AddToCartForm').submit(function() {
      console.log("Validation called");
      return false;
  });
});

We've modified the form add to cart form to have the AddToCartForm id. However, this function is never called. Logging the just $('#AddToCartForm') shows that the selector is working correctly. We also tried moving it to the product liquid page to be just under the form close tag, but that didn't change anything. We've also tried binding onto the submit button itself then using

e.preventDefault();
e.stopPropagation();

to stop the form from submitting, but this also does not work. However, it does bind and the function is called properly, it just doesn't stop the submission. We've been trying all day to fix this, and are completely out of ideas, any help is much appreciated. 

Thank you!

EDIT:

We also actually also tried using onSubmit, so the code was:

<form onSubmit='return test()'>

The js was:

function test() {
  console.log("Validation called");
  return false;
}

this function was also never called.

Replies 5 (5)
William22
New Member
10 0 0

Hey I have the exact same problem! I also have tried vanilla javascript

document.getElementById("AddToCartForm").onsubmit = function() {}

and   

document.getElementById("AddToCartForm").addEventListener('submit', function);

but as expected nothing different happens.
You can add functions to the addtocart button, but this leaves open the possibility of someone writing 

document.getElementById("AddToCartForm").submit()

into the console and bypassing it.

Zeeshan_Mahmood
Shopify Partner
6 0 3

Exactly. You can even do more hacky things where you change the add to cart button to type='button' rather than type='submit', then call $('AddToForm').submit() if validation passes, but it has the same issue you mentioned, that people can easily bypass it. 

William22
New Member
10 0 0

Try posting this under APIs and Technology, it may receive a bigger audience there https://ecommerce.shopify.com/c/shopify-apis-and-technology

Zeeshan_Mahmood
Shopify Partner
6 0 3

I re-posted it there. Thank you!

HardikM
Shopify Partner
13 1 4

@Zeeshan_Mahmood 

do update the link to the issue in your previous message itself, so that 1 visiting this can easily find it there