Item Validation

When it comes to adding an item to cart, you want to ensure the item is valid before making the request to the server. That is, ensuring the variation, options, and/or modifiers are all valid. The SDK supplies a convenient function that combines all these checks. After any item selection updates, you can use it to update your UI if it throws an error (e.g. disable your add to cart button), or alternatively only check when the buyer tries adding to cart and displaying an error if one is thrown.

Usage

The validateItem function takes in the following object:

interface ValidateItemRequest {
    item: Item;
    selectedOptions?: OptionSelection[];
    selectedModifiers?: AddItemModifier[];
    selectedVariationId?: string;
    quantity?: number;
}
  • item is the item resource you’re validating.
  • selectedOptions is an array of OptionSelections, which is used in variation choices.
  • selectedModifiers is an array of AddItemModifiers which is used in modifier validation.
  • selectedVariationId is used in lieu of selectedOptions if you have a flat variation. It’s simply the id on the choice in the item.variations array. Alternatively, it is also possilbe to use this for variations with multiple options had you chosen to display the raw variations available.
  • quantity can be added if you have a quantity selector and want to validate that there is enough quantity available if you’re tracking inventory and/or the quantity obeys the per order max if configured. Note this does not take into account any quantity in an existing order, and this specific error scenario will need to be caught when adding the item(s) to a cart order.

A couple of example usages:

sdk.helpers.item.validateItem({
    item: item,
    selectedOptions: [
        {
            "itemOptionId": "FPWZK5NMPZSUJ6V2SKYMYKS7",
            "choice": "Medium"
        },
        {
            "itemOptionId": "V4ZLC5E7ZIRJQHBKQVSXITGU",
            "choice": "Home"
        }
    ],
    selectedModifiers: [
        {
            "id": "CEO4PNPOCG6XL4NO27O3EJES",
            "type": "CHOICE",
            "choiceSelections": [
                "Q5AHPUFNSP2AA5GP2JY73Z4D"
            ]
        },
        {
            "id": "11ee26523c56faf08d928e0f9ddeceab",
            "type": "TEXT",
            "textEntry": "Text Modifier"
        }
    ]
})
sdk.helpers.item.validateItem({
    item: item,
    selectedVariationId: 'EV5HF3SFJQCF64MY7SRRPFMB',
    quantity: 2
})
// Don't need selectedVariationId if it's a single variation, it will be ignored.
sdk.helpers.item.validateItem({
    item: item
})

Return value and error handling

If validateItem is successful, it will return an AddLineItem object which can be used in the SDK’s cart functions.

{
    itemId: string;
    variationId: inStockVariation.id;
    modifiers: selectedModifiers;
    quantity?: number;
}
  • quantity is included if you passed quantity in the ValidateItemRequest object

You may optionally add any other remaining properties on the AddLineItem object afterwards.

interface AddLineItem {
    itemId: string;
    variationId: string;
    quantity?: number;
    modifiers?: AddItemModifier[];
    priceOverride?: {
        amount: number;
        currency: CurrencyTypeEnum;
    };
    subscriptionPlanVariationId?: undefined;
}

Example happy path usage with no error handling:

const addLineItem = sdk.helpers.item.validateItem({
    item: item,
    selectedVariationId: 'EV5HF3SFJQCF64MY7SRRPFMB'
});
sdk.cart.addItem({
    lineItem: addLineItem,
    fulfillment: fulfillment,
    locationId: locationId
});

On any validation failure, validateItem will throw a ValidateItemError.

interface ValidateItemError extends Error {
    itemOptionIds?: string[];
    flatVariationSelectionMissing?: boolean;
    variationId?: string;
    quantityErrorType?: QuantityErrorTypeEnum;
    modifierListIds?: string[];
}

validateItem will populate the ValidateItemError with the properties that match any of the invalid selections.

  • itemOptionsIds will include an array of ids from the item.item_options for each item option that is missing in selectedOptions (either not finding a matching id or a matching choice in the choices array if the id match is found). If selectedVariationId is set, then this will never be populated.
  • flatVariationSelectionMissing will be set to true if there’s no selectedVariationId provided for a flat variation with multiple variations.
  • variationId will include the variation id (from a variation in the item.variations array) if the matching variation for selectedVariationId or selectedOptions has a quantity error (populated in quantityErrorType).
  • quantityErrorType reflects the quantity error that goes with the variationId. Both will always be populated together. It will be one of the types in the block below. You can use these to determine what error message to show in your UI.
      const QuantityErrorType = {
          INVALID_QUANTITY: 'INVALID_QUANTITY',
          SOLD_OUT: 'SOLD_OUT',
          STOCK_EXCEEDED: 'STOCK_EXCEEDED',
          PER_ORDER_MAX_EXCEEDED: 'PER_ORDER_MAX_EXCEEDED'
      };
    
    • INVALID_QUANTITY is set if the quantity passed in the ValidateItemRequest is smaller than 1 (i.e. 0 or negative).
    • SOLD_OUT is set if the variation is sold out. Note that this will always be set if variationId is set and there was no quantity passed in the ValidateItemRequest.
    • STOCK_EXCEEDED is set if the quantity passed in the ValidateItemRequest exceeds the available stock available for a variation (assuming stock tracking is enabled).
    • PER_ORDER_MAX_EXCEEDED is set if the quantity passed in the ValidateItemRequest exceeds the per order max for an item (assuming it was configured).
  • modifierListIds will include an array of ids from the item.modifier_lists for each modifier list that is invalid in selectedModifiers (including if the modifier list is required and not included in selectedModifiers).

Note that none of the properties will be populated if no match is found for selectedVariationId.

try {
    const addLineItem = sdk.helpers.item.validateItem({
        item: item,
        selectedVariationId: 'EV5HF3SFJQCF64MY7SRRPFMB'
    });
} catch (validateItemError) {
    // Handle validate item errors however you wish
    if (validateItemError.itemOptionsIds) {
        console.log('Invalid item option ids:', validateItemError.itemOptionsIds);
    }
    if (validateItemError.errorVariationId) {
        console.log('Invalid variation id:', validateItemError.errorVariationId);
    }
    if (validateItemError.modifierListIds) {
        console.log('Invalid modifier list ids:', validateItemError.modifierListIds);
    }
}