Logic & flow

Validation

Author per-question checks beyond the built-in `required` / `min` / `max`. Write Python in a `validation:` block; call `fail("message")` to reject the answer with a custom error.

What validation: is

validation: is a per-question Python block that runs when the respondent tries to advance past a question. It’s the place to write checks the standard properties (required, min, max, exact, decimal) can’t express on their own.

- qid: QZip
    type: open
    text: What's your ZIP code?
    default.errors: False
    validation: |
        if not re.fullmatch(r"\d{5}", QZip.value):
            fail("Please enter a valid 5-digit ZIP code.")
    input.size: 8

The block runs every time the respondent submits the page. If fail(...) is called, the answer is rejected and the message shows next to the question. If the block finishes without calling fail, the answer is accepted.

Why validation matters

Three things validation: does that the everyday properties don’t:

  • Cross-field checks. Compare two answers, sum a list, gate one question on another.
  • Format checks. Regex against a typed value (ZIP code, email, phone number).
  • Custom messaging. Replace the engine’s default error with a friendlier line.

For simple bound checks, prefer the built-in properties — they’re clearer to read and don’t need a code block:

# Don't write this validation —
- qid: QAge
    type: number
    validation: |
        if QAge.value < 13 or QAge.value > 120:
            fail("Please enter a realistic age.")

# — when this gives you the same effect:
- qid: QAge
    type: number
    min: 13
    max: 120

Reach for validation: when the built-ins can’t say what you mean.

The fail(...) helper

fail(message) is the runtime helper that rejects the answer and shows an error.

ArgumentTypeMeaning
messagestringThe text shown to the respondent next to the question. Pipe-aware — {{ ... }} placeholders resolve at render time. Language-aware too — the runtime renders the message in the respondent’s active language using the survey’s translation context.

Call fail once for each rejection condition. The first fail that fires shows its message; subsequent rejections in the same block don’t replace it.

- qid: QEmail
    type: open
    validation: |
        if not re.fullmatch(r"[^@\s]+@[^@\s]+\.[^@\s]+", QEmail.value.strip()):
            fail("Please enter a valid email address.")
The first fail wins. If multiple fail(...) calls fire in one block, the runtime records them all but only surfaces the first one to the respondent. Order your conditions so the most informative message comes first.

Storing error messages in a hidden multi

Hard-coding error strings inline gets noisy when the same message appears in several places, or when copy needs reviewing without touching validation logic. The everyday workaround: park the messages on a hidden multi question and pull them through .row(N).label.

- lists:
    errMessages:
        options:
            1: Please enter your partner's name.
            2: Please enter a valid 5-digit ZIP code.
            3: Please enter a valid email address.

- qid: QErrMsg
    type: multi
    visibility: hide
    text: Validation error messages
    options: errMessages

- qid: QPartnerName
    type: open
    text: Partner's name
    validation: |
        if QPartnerName.value == "":
            fail(QErrMsg.row(1).label)

QErrMsg never renders to the respondent — visibility: hide keeps it out of the flow — but its option labels are readable from any validation block via QErrMsg.row(N).label. Edit the list once, every fail that references it picks up the new copy.

This also gives translators a single place to work: the messages sit in a - lists: block alongside the rest of the survey’s authored text, not scattered through Python code.

default.errors: False — turn off built-in messages

When you author validation:, you usually also want to disable the engine’s default error text (which fires for things like “empty when required: True”). Add default.errors: False so your custom message is the only one shown.

- qid: QPhone
    type: open
    text: What's your 10-digit mobile number?
    default.errors: False
    validation: |
        if not re.fullmatch(r"\d{10}", QPhone.value.strip()):
            fail("Please enter a valid 10-digit phone number.")
    input.size: 14

Without default.errors: False, the respondent might see both the built-in “this question is required” message and your custom message stacked.

What you can write inside

The validation block is a Python-subset code block. Available:

  • All Q.* accessors for reading the question’s own value and any other question’s answer
  • Python control flow (if / elif / else, for, while)
  • Built-in functions: len, sum, min, max, int, float, bool, abs, round, plus the Fieldbase safe set
  • Safe modules: math, random, re, datetime
  • The runtime helpers: fail, print, endSurvey

Not available: list / dict comprehensions, lambda, generators, file I/O, network calls. See Python essentials for the full subset.

Examples

Regex format check

- qid: QZip
    type: open
    text: What's your ZIP code?
    default.errors: False
    validation: |
        if not re.fullmatch(r"\d{5}", QZip.value):
            fail("Please enter a valid 5-digit ZIP code.")
    input.size: 8

re.fullmatch requires the entire input to match — guards against trailing characters that re.match would let through.

Cross-question consistency check

- qid: LivingSituation
    type: multi
    text: Which best describes your household?
    options:
        1: Live alone
        2: Live with a partner
        3: Live with parents or guardians
        5: Live with roommates
        6: Live with siblings
        7: Single parent living with children
        99:
            label: Prefer not to answer
            anchor: True
            exclusive: True
    validation: |
        if (LivingSituation.selected.every([5, 6])
                or (LivingSituation.selected.any(1) and LivingSituation.selected.size > 1)
                or (LivingSituation.selected.any(7) and LivingSituation.selected.any([5, 6]))):
            fail("Please review your answer.")

Catches contradictory combinations — living alone + anything else, single parent with children + with roommates, etc. A single fail covers all the impossible cases.

Sum-equals-target on a numberList

- qid: QAlloc
    type: numberList
    text: Allocate 100 points across these categories.
    options: spendCategories
    min: 0
    max: 100
    validation: |
        total = 0
        for c in QAlloc.all:
            total = total + (QAlloc.row(c).value or 0)
        if total != 100:
            fail("Allocations must sum to exactly 100. You have {{ total }}.")

The error message includes the current total via {{ total }} piping, so the respondent knows immediately how much they’re off by. See Piping for the full templating surface.

Range with a friendlier message

- qid: QSpend
    type: number
    text: About how much do you spend per month?
    label.prefix: $
    decimal: True
    decimal.places: 2
    min: 0
    max: 5000
    validation: |
        if QSpend.value < 0 or QSpend.value > 5000:
            fail("Please enter a realistic monthly spend.")

The min / max already enforce the range — but the engine’s default message is generic. The custom fail replaces it with something more conversational.

Conditional validation — only check when relevant

- qid: QPartnerName
    type: open
    text: What's your partner's first name?
    validation: |
        if QHasPartner.value == 1 and len(QPartnerName.value.strip()) == 0:
            fail("Please enter your partner's name.")

Validates the question only when the respondent has indicated they have a partner. Without this, an empty partner-name on a single respondent would trigger a spurious error.

When validation runs

The block runs when the respondent advances past the page containing the question. If a single page has several questions with validation: blocks, each block runs in turn; the page holds at the first fail and shows that question’s error.

Validation does not run on every keystroke. It only runs at submission, so the respondent can type freely without interruption.

See also

  • Python essentials — the language subset available inside validation: and - script:
  • Routing — if: for hiding the question entirely (different mechanism, different intent)
  • Q.* accessors — what you can read in a validation expression
  • Properties — built-in required, min, max, exact, decimal