Restricting specific items to country

Hi there,

I am trying to restrict one of my items to only be ordered if the shipping country is set to United States, but can’t quite figure out how to do it. I’ve tried using the validation event in a wacky way:

var hasSpecificItem = false
Snipcart.subscribe('page.validating', function (ev, data) {
	switch (ev.type) {
		case 'cart-content':
			for (i = 0; i < data.length; i++) {
				if (data[i].id == 'item_id') {
					hasSpecificItem= true;
				}
			}
			break;
		case 'shipping-address':
			console.log(data);
			if (hasSpecificItem && data.country != 'US') {
				ev.addError('country', 'Error content.');
			}
	}
});

but it looks like the page.validating event can only be used for 1 page. I’ve tried both with and without the break; statement at the end of the first case.

Is there a better way to do this, or something I’m missing?

Thanks!

Hi there,

The page.validating event will not trigger if an item is added to the cart, only when a form in the checkout process is submitted.

In your case, you may want to subscribe to 2 events instead of one:
First, the item.adding or item.add event to set the “hasSpecificItem” variable.
Second, the page.validating to validate the shipping address when the “hasSpecificItem” variable is true.

I hope this helps, cheers!

page.validating documentation: Events – Snipcart Documentation.
item.adding documentation: Events – Snipcart Documentation
item.added documentation: Events – Snipcart Documentation