shopifyliquidshopify-template

How to validate Shopify theme settings?


With Shopify API you can set up input fields for user to adjust theme, for example:

{
  "type": "number",
  "id": "products_per_page",
  "label": "Products per page",
  "default": 20
}

Shows a checkbox in the page theme admin panel sidebar. However, user can set an invalid value, for example -2.

In that case, what I understand, I can change liquid file to display an error message.

However, the problem is, that when user will not notice the error, it will be visible to other users.

So my question is: how to validate Shopify theme settings?

Is there a way to display error messages in the sidebar next to input fields, or to display error message in the liquid only to the admin?


Solution

  • Unfortunately, no: Shopify does not allow custom validation for theme settings through the admin tools

    If you want to enforce constraints on any of the inputs in the theme settings, you are restricted to the controls on the data types available:

    If these limited use cases can't cover your validation logic, then unfortunately there isn't anything you can do to specify your own validation formula that will be enforced during theme setting updates.

    There is a (slightly hacky) way to show an error only in the theme customizer, however

    Using this trick shared in the Shopify Community, you can check the contents of content_for_header to test for one of the scripts injected when viewing the theme through the customizer preview:

    {% if content_for_header contains "Shopify.designMode" %}
      Customizer
    {% else %}
      Live!
    {% endif %}
    

    This would let you write a snippet that could test any settings with complex validation logic and display a big ol' error bar on the theme customizer page if the settings don't check out while not alarming any shoppers on the actual site.

    Note that this will rely on the injected code that you test for to be present - if Shopify updates their code injection in the future this trick would stop working/would need to be updated to test for whatever they update the customizer code injection to.