Custom Validation

Basics

To add custom validation logic, you will need to subscribe to our page.validating event:

Snipcart.subscribe('page.validating', function(ev, data) {
    if(ev.type == 'shipping-address' && data.phone.substr(0, 3) != '+1.') {
        ev.addError('phone', 'Please enter a US or Canadian phone number');
    }
});

The callback receives an Event object and the data of the page.


Event object

The event object is the first parameter of the validation callback. It allows you to stop the processing of a cart's page and to add error message to the page.

It's based on the browser's standard event object for familiarity.

Event.type

string representing the page to validate.

It can be one of: cart-content, order-infos, shipping-address, billing-address or order-confirm.

Event.addError(key, message)

Add an error message to the current view and prevent the customer from continuing to the next page.

The key is the field or item that should receive the error message.

Event.preventDefault()

For special cases where you don't want to use the built-in view to display error messages, you can call ev.preventDefault() to make the validation fail and stop the customer from going to the next step of the cart.


Pages' data

Page name Event.addError's key Data
cart-content

Product's id from data-item-id or the uniqueId field's value from the item.

List of items in the cart.

order-infos

Custom field's name or id.

List of custom fields on the cart.

billing-address

One of the address field's name.

The address object with all the address' fields.

shipping-address

One of the address field's name.

The address object with all the address' fields.

* won't fire if customer has checked to use the same address as the billing address

order-confirm

The key is ignored for order-confirm. The message will appear at the top of the order confirmation page.

The full content of the cart.