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;
}
itemis the item resource you’re validating.selectedOptionsis an array ofOptionSelections, which is used in variation choices.selectedModifiersis an array ofAddItemModifiers which is used in modifier validation.selectedVariationIdis used in lieu ofselectedOptionsif you have a flat variation. It’s simply theidon the choice in theitem.variationsarray. Alternatively, it is also possilbe to use this for variations with multiple options had you chosen to display the raw variations available.quantitycan 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;
}
quantityis included if you passedquantityin theValidateItemRequestobject
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.
itemOptionsIdswill include an array ofids from theitem.item_optionsfor each item option that is missing inselectedOptions(either not finding a matchingidor a matching choice in thechoicesarray if theidmatch is found). IfselectedVariationIdis set, then this will never be populated.flatVariationSelectionMissingwill be set totrueif there’s noselectedVariationIdprovided for a flat variation with multiple variations.variationIdwill include the variationid(from a variation in theitem.variationsarray) if the matching variation forselectedVariationIdorselectedOptionshas a quantity error (populated inquantityErrorType).quantityErrorTypereflects the quantity error that goes with thevariationId. 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_QUANTITYis set if thequantitypassed in theValidateItemRequestis smaller than 1 (i.e. 0 or negative).SOLD_OUTis set if the variation is sold out. Note that this will always be set ifvariationIdis set and there was noquantitypassed in theValidateItemRequest.STOCK_EXCEEDEDis set if thequantitypassed in theValidateItemRequestexceeds the available stock available for a variation (assuming stock tracking is enabled).PER_ORDER_MAX_EXCEEDEDis set if thequantitypassed in theValidateItemRequestexceeds the per order max for an item (assuming it was configured).
modifierListIdswill include an array ofids from theitem.modifier_listsfor each modifier list that is invalid inselectedModifiers(including if the modifier list is required and not included inselectedModifiers).
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);
}
}