Skip to content

Custom Checkout Validation with Shopify Functions: 2026 Guide

The Cart and Checkout Validation Function API is the only server-side way to block a Shopify cart or checkout that breaks your rules. This guide covers plans, limits, how errors appear and a tested example.

Custom Checkout Validation with Shopify Functions: 2026 Guide

To add custom checkout validation on Shopify, you build a Shopify Function on the Cart and Checkout Validation Function API, ship it inside an app, and turn it on as a checkout rule under Settings > Checkout. The function runs on Shopify's servers in the cart and at checkout, including express checkouts such as Shop Pay, PayPal, Google Pay and Apple Pay, and it blocks the order with a message you write when the cart breaks one of your rules.

It is the only way to validate a cart and checkout server-side on Shopify. Stores on any plan can use a public App Store app that contains a validation function. A custom app built only for your store needs Shopify Plus. This guide covers what the API can check, the plans and limits, how errors appear in checkout, and a working example, all checked against Shopify's API reference for version 2026-10.

What can a checkout validation function check?

A validation function reads the cart through a GraphQL input query and returns errors. Shopify lists these use cases:

  • tokengating, or requiring a customer membership at checkout;
  • verifying a customer's age or ID during checkout;
  • B2B product minimums, maximums and multiples;
  • B2B location order minimums, maximums or credit limits;
  • quantity limits during a flash sale;
  • validating purchase order numbers for B2B customers;
  • billing address restrictions.

Shopify's own examples add blocking PO box addresses, requiring a gift note, requiring local tax fields at the final step, and limiting a product's quantity with a value stored in a product metafield.

The input can include cart lines and quantities, product and variant data, product and customer metafields, cart attributes, the buyer's identity (including the customer's number of orders), delivery and billing addresses, B2B company data and localized checkout fields. A function can't use randomness or the clock, and it can't call your own API unless it is a custom app on an Enterprise store with network access approved. For anything else, pass the data in through metafields or cart attributes.

Which plans can use checkout validation functions?

SetupWho can use it
A public app from the Shopify App Store that contains a validation functionStores on any plan
A custom app with your own validation functionShopify Plus stores
The fetch target, which lets the function call an external APICustom apps on Enterprise stores, after requesting network access. Not available on development stores.
Checkout UI extensions on the information, shipping and payment steps, for in-page checksShopify Plus stores

So a non-Plus store gets validation through apps, and a Plus store can also build its own. Shopify's free Checkout Blocks app, for example, includes an order limit validation built on Shopify Functions that blocks checkout outside a minimum or maximum subtotal.

What are the limits?

LimitValue
Active validation functions per store25
Instructions per run (carts up to 200 lines)11 million
Function input128 kB
Function output20 kB
Input query cost30
Input query size, without comments3,000 bytes
Compiled binary256 kB
Runtime linear memory10,000 kB

The instruction, input and output limits scale up for carts with more than 200 lines. Language choice matters here. In Shopify's own quantity-limit example, which the code below is based on, the Rust version uses about 19,000 instructions and the JavaScript version about 183,000. Both fit easily, but Shopify recommends Rust as the most performant choice, which counts when the logic is heavy or carts are large.

Where do validation functions run?

SupportedNot supported
Online store cart and checkout, including accelerated checkoutsPoint of Sale
Headless carts built on the Storefront APISubscription renewals (recurring orders)
B2B checkoutsOrder edits, in the admin or in checkout
Draft orders, in the admin and in checkoutOrders created with the Create Order API
Shopify adminPre-orders and try before you buy

Checkout rules also apply to draft orders by default. Staff can override them before completing a draft order.

How are validation errors shown in checkout?

Every error your function returns has two parts: a message the customer reads and a target that decides where it appears.

TargetWhere the message appears
$.cartAt page level, on the checkout step the customer is on
$.cart.buyerIdentity.emailUnder the email field
$.cart.deliveryGroups[0].deliveryAddress.zipUnder the shipping postal code (address1, city, countryCode, provinceCode and the other address fields work the same way)
$.cart.billingAddress.countryCodeUnder the billing country
$.cart.poNumberUnder the purchase order number (B2B)
$.cart.localizedField.KEYUnder a localized field, such as a tax ID

Outside checkout, Shopify exposes the same errors on the Storefront API's Cart object and in themes that use the cart template. In the Storefront API, a cart mutation such as cartLinesAdd fails and returns a user error with the code VALIDATION_CUSTOM. If your theme uses a cart drawer or a custom cart, test that it shows these messages, because a customer who can't see the reason will simply leave.

The input also tells you where the customer is, through buyerJourney.step:

  • CART_INTERACTION: the customer is changing the cart;
  • CHECKOUT_INTERACTION: the customer is moving through checkout;
  • CHECKOUT_COMPLETION: the customer is placing the order.

Use the step to block at the right moment. Shopify's example for required tax fields only checks at CHECKOUT_COMPLETION, so customers aren't stopped while they are still filling in the form. A quantity limit, on the other hand, is best shown in the cart, before the customer reaches checkout.

Write messages that say what is wrong and how to fix it. "Orders over $1,000 need an account with at least five previous orders" works. "Validation failed" doesn't.

How do you build a checkout validation function?

You need a Shopify CLI app installed on a development store, Node.js, and API version 2025-07 or later. The example limits how many units of a product a customer can buy, using a product metafield, so the merchant can change limits without a new deployment.

  1. Generate the extension from your app folder and pick Rust, JavaScript, TypeScript or Wasm when asked:
    shopify app generate extension --template cart_checkout_validation --name cart-checkout-validation
  2. Write the input query in src/cart_validations_generate_run.graphql. It asks only for what the rule needs:
    query CartValidationsGenerateRunInput {
      cart {
        lines {
          quantity
          merchandise {
            __typename
            ... on ProductVariant {
              product {
                title
                metafield(namespace: "custom", key: "max_per_order") {
                  value
                }
              }
            }
          }
        }
      }
    }
  3. Write the logic in src/cart_validations_generate_run.js:
    // @ts-check
    
    /**
     * @typedef {import("../generated/api").CartValidationsGenerateRunInput} CartValidationsGenerateRunInput
     * @typedef {import("../generated/api").CartValidationsGenerateRunResult} CartValidationsGenerateRunResult
     */
    
    /**
     * @param {CartValidationsGenerateRunInput} input
     * @returns {CartValidationsGenerateRunResult}
     */
    export function cartValidationsGenerateRun(input) {
      const errors = [];
    
      for (const line of input.cart.lines) {
        if (line.merchandise.__typename !== "ProductVariant") {
          continue;
        }
    
        const product = line.merchandise.product;
        const limit = parseInt(product.metafield?.value ?? "", 10);
    
        if (!Number.isNaN(limit) && line.quantity > limit) {
          errors.push({
            message: `You can buy up to ${limit} of ${product.title} per order.`,
            target: "$.cart",
          });
        }
      }
    
      return { operations: [{ validationAdd: { errors } }] };
    }
  4. Generate types and preview it. In JavaScript, regenerate types after every change to the query, then start the dev preview:
    shopify app function typegen
    shopify app dev
    The dev output lists each function run with its logs. shopify app function replay runs a past execution again while you fix the code.
  5. Add the data. Create an integer product metafield definition, custom.max_per_order, and set it on the products that need a limit.
  6. Release it with shopify app deploy and install the app on the live store.

Functions written before API version 2025-07 use the target purchase.validation.run. From 2025-07, Shopify renamed it to cart.validations.generate.run and the function now returns operations with validationAdd, as in the example. Older versions keep working, but upgrading the API version means updating the code.

How do you turn on a checkout rule in the Shopify admin?

  1. Go to Settings > Checkout.
  2. Click Checkout rules, then Add rule.
  3. Pick the rule your app provides and choose its settings.
  4. Optional: deselect Allow all customers to complete checkout if orders must not go through when the rule itself fails with an error.
  5. Click Save, then Turn on.

That setting only covers runtime errors, when the function throws an exception or exceeds its resource limits. A function that runs and returns an error always blocks. To change, turn off or remove a rule later, open it from the same Checkout rules section.

Server-side functions or checkout UI extensions?

Validation functionCheckout UI extension
Where it runsOn Shopify's serversIn the customer's browser, inside checkout
CoversCart, checkout, express checkouts, Storefront API carts, draft ordersThe checkout steps where the extension is placed
How it blocksReturns errors with targetsIntercepts progress through the Buyer Journey API
PlansAny plan through public apps, Plus for custom appsInformation, shipping and payment steps need Plus
SetupCheckout rule in Settings > CheckoutNeeds the block_progress capability, and the merchant has to allow it in the checkout editor's checkout behavior settings
Best forRules that must hold for every orderFeedback inside a checkout step, before the customer moves on

Use an extension for feedback and a function for enforcement. The function is the one that covers every path to an order, including Shop Pay and other express buttons.

What should you test before going live?

  • Guest checkouts. buyerIdentity and customer can be empty, so treat a missing customer as a new one.
  • Express checkouts. Place a test order with Shop Pay or another accelerated button and confirm the rule still blocks.
  • The cart and the cart drawer. Check that the message appears where the customer will see it.
  • Split carts. A checkout can have more than one delivery group, for example shipping plus pickup. Shopify advises iterating over all delivery groups instead of assuming one.
  • Large carts. Test near your biggest real orders and keep the input query small, since every field costs instructions.
  • Runs in production. Shopify stores each function run, with its input and output, in the Dev Dashboard. Check it after launch and after every deployment.

Do you need a custom validation function at all?

Not always. Check these first:

  • Order minimums and maximums: Checkout Blocks has an order limit validation that needs no code.
  • B2B quantity rules: Shopify's B2B catalogs support minimum, maximum and increment rules per variant without a function.
  • Common rules such as age checks or purchase limits: an App Store app may already do it, on any plan.

A custom function makes sense when the rule depends on your own data, combines several conditions, or has to work across markets and B2B in one place. That is the work our checkout customization team does, usually together with a custom app and an admin screen where the merchant edits the rule. For the bigger picture of what you can change in checkout today, read our guide to Shopify checkout extensibility in 2026, and if B2B is the reason you're looking at validation, see whether you still need Shopify Plus for B2B.

FAQ

What is the Cart and Checkout Validation Function API?

It is the Shopify Function API for server-side cart and checkout validation. Your function reads the cart and returns errors with a message and a target. Shopify then stops the customer at that point and shows the message. It runs on Shopify's servers and covers express checkouts such as Shop Pay, PayPal, Google Pay and Apple Pay.

Do I need Shopify Plus for checkout validation?

Not to use it. Any plan can install a public App Store app that contains a validation function. You need Shopify Plus to run a custom app with your own validation function.

How do I create a validation in Shopify?

Install or build an app that contains a validation function, then go to Settings > Checkout, click Checkout rules, then Add rule, pick the rule, save it and click Turn on.

How many validation functions can a store use?

Up to 25 active validation functions per store.

Do validation functions work with Shop Pay and other express checkouts?

Yes. Shopify states that cart and checkout validation includes express checkouts such as Shop Pay, PayPal, Google Pay and Apple Pay.

Can a validation function call an external API?

Only through the fetch target, which is limited to custom apps on Enterprise stores with network access approved. Otherwise, put the data the function needs into metafields or cart attributes.

Need custom checkout logic?

We build checkout validation, discounts and UI extensions with Shopify Functions and Checkout Extensibility.

The checklist we run before touching a client's code

Get it by email, plus a few short notes over the next two weeks: what we see most often on Shopify stores and what actually fixes it.

No spam. Unsubscribe anytime. Privacy Policy

Want more of our posts in your Google results? Add Codersy as a preferred source.

Add Codersy on Google(opens in a new tab)