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?
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:
Range: Good for number ranges that have a min/max, but resolution is limited to the step
that you specify. Shopify also has a max of ~100 stepping-points between min and max, so if the range you have to cover is large enough this choice won't cover you
Select: Best for text options, and quickly becomes cumbersome if you have more than 6-8 options.
Radio: Also best for text options, and only where there are only a small number of choices.
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.
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.