CASE: Input validation with Regular Expressions (Regex)

While standard attributes like min or max are great for numbers, sometimes you need to validate specific formats like Tax IDs, IBANs, or custom reference codes.

This is where Regular Expressions (Regex) come in. By using the pattern attribute within input_validation, you can enforce strict formatting before the data is even stored.


Practical Example: Tax ID validation

Let’s look at a common scenario: a Tax ID that must follow a specific pattern (e.g., 00-00000000-0).

  1. Define the validation text

    {% t= "tax_id_validation_t" default:"Please use the correct tax id structure" %}

  2. Define the validation rule

    {% input_validation tax_id_validation pattern:"^\d{2}-\d{8}-\d$" validation_text:"tax_id_validation_t" %}

    Breaking down the Regex pattern: ^\d{2}\d{8}-\d$

  • ^ and $: These anchors ensure the entire input matches the pattern from start to finish.
  • \d{2} : Matches exactly 2 digits.
  • - : A literal hyphen (must be present in that exact spot).
  • \d{8} : Matches exactly 8 digits.
  • - : Another literal hyphen.
  • \d : Matches exactly 1 digit.
  1. Apply it to an input field

    {% input custom.tax_id.validation placeholder:"00-00000000-0" validation:tax_id_validation %}

  2. Output

    image


Unlike numeric or date validations, the system cannot automatically generate a readable error message for a Regex pattern. Because a Regex can be anything from a simple digit to a complex sequence, Liquid won’t know how to explain the “rule” to the user in plain text. You’ll need to use the validation_text attribute to explain the required format to your users. We recommend using a translation key (e.g., "tax_id_validation_t") so your templates remain multi-lingual and user-friendly.