How can I validate custom fields on buy button with a listener event and prevent the item being added to the cart?

Validating custom fields before items are added to the cart is proving tricky.

It seems the only way is:

  • Config cart not to load with product behaviour none
  • Validate and then open the cart via Snipcart.api.theme.cart.open()

However I have found that the item gets added regardless.

So it looks like the only solution is for it to be added to the cart and then for me to remove it.

I thought the event ‘item.adding’ might allow me to intercept the adding to cart but no unique Cart Id is produced in this event so no action can be taken. I am having to use the on item.added event to get a uniqueId then remove item from cart if validation fails.

This works but has the annoying UI quirk that an item is added and visible in the design basket count and then disappears when validation fails.

Is there a better way around this?

1 Like

If you’re happy using events and API, I’d suggest removing the data-properties on the cart button that are doing the automatic add, and using Snipcart.api.items.add({item}) after your own validation. You’ll need to recreate the data-properties in a js item Object instead.

1 Like