Skip to content

M4-S2 — Validators, interceptors, and choosing the right tool

Section titled “M4-S2 — Validators, interceptors, and choosing the right tool”
ModuleM4 — Functions: code where the designer stops
After this session you canStop bad data at the door with your own rules, and choose the right tool for any rule a suite needs.
TimeFacilitated: 48 min · On your own: 48 min
Before you startM4-S1: you can build, test and deploy a Function. The public Job Application form, reachable from Available jobs in a private window.
Go deeperValidators · Request interceptors · Webhooks & integrations: interceptors

◆ Orientation (1 min) — A late requirement

Section titled “◆ Orientation (1 min) — A late requirement”

A week after go-live is planned, HR’s screening lead brings a new rule: an application must not say the candidate is available from a date already past, and Expected salary, a text field in the tutorial’s design, must hold a number or nothing. The designer has no option for “not before today” across a public form, and the salary rule is about the shape of typed text. Both belong in a validator: a Function that the platform asks before it saves.

▤ Concept (5 min) — Functions that guard, and how to choose

Section titled “▤ Concept (5 min) — Functions that guard, and how to choose”
Standalone ValidatorValue Validator
ChecksThe whole recordOne field’s value
Receives{ dataEntry, existingEntry }{ value }
RunsBefore the record is saved, edited or archived: you choose which when you attach itWhen the record is saved
A refusal showsThe messages for the error codes it returnedThe message on the field

A validator runs only where a builder attaches it to an entity, and only for records of the entity in its scope. It answers { success: true } or { success: false, errors: [{ errorCode: '…' }] }. Each error code is looked up in the function’s Errors list, where you enter the message people see. The first validator that returns errors stops the save.

Choose when it runs as carefully as what it checks. A rule about a new application (“not available from a past date”) must not run when HR edits the application a month later, or every old application would be refused once its date had passed.

An Interceptor runs before an incoming request that matches its path and method, and may rewrite the request or answer it itself. Interceptors run in priority order, only before the request is handled (there is no “after”), and they fail open: if one fails or answers something unreadable, it is skipped and the request continues. So an interceptor can adjust or short-cut a request, but it is never the thing that keeps data safe.

The ruleToolWhat it guarantees
Do something after an eventReactionRuns in the background; failures are logged, not shown
A value from the record’s own fieldsExpressionLive in the form and on save; quietly wrong if mistyped
Logic the designer cannot hold, a rule table, an outside callFunction via Execute FunctionYour code, versioned and tested; runs after the event
Refuse bad data before it is storedValidator FunctionNothing invalid is saved, from the form, a reaction or the API
Reshape or answer a request before it is handledInterceptor FunctionConvenience only: it fails open
flowchart LR
  REQ["Incoming request"] --> I["Interceptors<br/>(fail open)"] --> V["Validators<br/>(first error stops it)"] --> S[("Saved")]
  S --> R["Reactions<br/>(after, in the background)"] --> F["Execute Function<br/>(after)"]

What to notice: only a validator stands between bad data and the store; everything to its right acts after the fact, and an interceptor can be skipped.

⛏ Lab (33 min) — The application check

Section titled “⛏ Lab (33 min) — The application check”

Goal. A standalone validator refuses a new application whose Available from is in the past or whose Expected salary is not a number, with clear messages, and leaves later edits alone.

Before you start. A terminal in your working folder.

Write and test it

  1. Copy your M4-S1 project as application-check (cp -r offer-package application-check), go into it, and delete params.yaml (a validator takes no parameters). In func.yaml and package.json, change the name to application-check.

  2. Replace src/index.ts with:

    import { Context } from 'faas-js-runtime';
    type ValidationError = { errorCode: string };
    const handle = async (context: Context) => {
    const body = (context.body ?? {}) as any;
    const { dataEntry } = body.data ?? body;
    const v = dataEntry?.value ?? {};
    const errors: ValidationError[] = [];
    // Rule 1: not available from a date that has already passed
    const today = new Date().toISOString().slice(0, 10);
    if (typeof v.available_from === 'string' && v.available_from.slice(0, 10) < today) {
    errors.push({ errorCode: 'AVAILABLE_FROM_IN_PAST' });
    }
    // Rule 2: expected salary is empty or digits only
    const salary = v.expected_salary;
    if (salary !== undefined && salary !== null && String(salary).trim() !== ''
    && !/^\d+$/.test(String(salary).trim())) {
    errors.push({ errorCode: 'EXPECTED_SALARY_NOT_A_NUMBER' });
    }
    return errors.length ? { success: false, errors } : { success: true };
    };
    export { handle };
  3. Run npm install, npm run build and npm start. In a second terminal:

    Terminal window
    curl -s -X POST http://localhost:8080 -H 'Content-Type: application/json' \
    -d '{"dataEntry": {"value": {"available_from": "2020-01-01", "expected_salary": "about 9k"}}}' | jq
    curl -s -X POST http://localhost:8080 -H 'Content-Type: application/json' \
    -d '{"dataEntry": {"value": {"available_from": "2099-01-01", "expected_salary": "9000"}}}' | jq

    The first answers two errors; the second {"success": true}.

  4. Stop it and package it: zip -r ../application-check.zip . -x 'node_modules/*' 'build/*'.

Deploy and attach it

  1. In Administration › Applications › Functions, select Add Function: Name application-check, Type Standalone Validator, Function Scope Entity, Job Application; upload the ZIP.
  2. Under Errors, add the two codes with their messages: AVAILABLE_FROM_IN_PAST, The “Available from” date has already passed. Choose today or a later date.; EXPECTED_SALARY_NOT_A_NUMBER, Write the expected salary as a number only, for example 9000. Save, and wait for Provisioned.
  3. In the Job Application entity builder, open Form Settings, then the Standalone Validator panel, and select Add Standalone Validator. Choose application-check in Standalone Function and Before Save in Standalone Trigger, so that it runs before a new record is saved, not before edits (Before Edit) or archiving (Before Archive).

Prove it

  1. In a private window, not signed in, open Available jobs, choose HR Coordinator and apply as Mira Haddad, mira.haddad@example.org, Available from yesterday, Expected salary about 9k. Submit: the form refuses it and shows both messages.
  2. Correct the date to next month and the salary to 9000, and submit: the application is accepted.
  3. As Hala Mansour, open an older application, for example Rami Toufic, whose Available from is now in the past, and save a comment on it: the save is accepted, because the check runs only for new records.

Check.

  • The two local cases answer two errors and success: true.
  • application-check is a Provisioned Standalone Validator scoped to Job Application, with two error messages.
  • It is attached to run before a new record is saved only.
  • The public form refused Mira Haddad’s first attempt with both messages and accepted the corrected one.
  • HR could still edit an older application.

Pass condition. A visitor cannot submit an application with a past date or a non-numeric salary, sees why, and HR’s later edits are never blocked by the check.

If something goes wrong

What you seeWhat to do
The form shows a code, not your messageThe code under Errors does not match the code the function returns, letter for letter.
Every application is refusedTest locally with a valid record: a date compared as a date object instead of a string, or a missing ?? {}, refuses everything.
Nothing is refusedThe validator is not attached, is attached to edits only, or is not Provisioned.
HR’s edits are refusedIt is attached before edits too; attach it before a new record is saved only.
Model answer

The validator reads the record from body.data ?? body, checks two rules, and returns every error it found at once, so the visitor fixes both in one go. The messages live in the function’s Errors list, so HR can reword them without a rebuild. It is attached before a new record is saved and nowhere else, which is a design decision, not a detail: the date rule is only true at the moment of applying. Because the check runs on the server, it holds for the public form, a reaction or an API client alike.

◇ Worked scenario (2 min) — Four rules, four tools

Section titled “◇ Worked scenario (2 min) — Four rules, four tools”

A security reviewer and two team leads bring four rules. Choose the tool for each before reading on.

1. “Reject applications from disposable email domains.” It must stop bad data before it is stored. Choice: a validator. An interceptor could look at the request first, but it fails open: on its first error, every disposable address would get through.

2. “Every job title is stored in title case, however HR types it.” Choice: an expression on a hidden or locked copy, or simply a habit; not a Function. Reshaping one field of the record is the expression’s job.

3. “Old mobile app versions still post the phone number under a retired field name; map it to the new one until they update.” Choice: an interceptor that rewrites the body of that one request path. It is a convenience: if it is skipped, the request fails validation in the usual way, so nothing unsafe gets in.

4. “When an offer is signed, ask the background-check provider to start, and store their case number.” Choice: a Function via Execute Function, after the event: an outside call whose result a chained reaction stores. It does not belong in a validator, which must answer quickly and has no business calling other companies before a save.

The test for each rule: must it stop something, reshape something, or do something after?

✓ Practice (6 min) — Check your choices

Section titled “✓ Practice (6 min) — Check your choices”
PracticeChoose one answer.

An interceptor that checks an access code before requests to a sensitive path crashes once a week. What happens to the requests during the crash?

  1. Explanation for A

    ✗ Incorrect

    Not this one: interceptors fail open, so a failing one is skipped. See interceptors.

  2. Explanation for B

    ✓ Correct

    Correct: a failed interceptor is skipped and the request goes on, which is why it is never a security control. See interceptors.

  3. Explanation for C

    ✗ Incorrect

    Not this one: the platform does not wait for a failed interceptor; it skips it. See interceptors.

Check your answer

The correct answer is B. Open the explanation under each option to see why.

PracticeChoose one answer.

A validator rejects a leave request whose start date is in the past. It is attached before save and before edit. What goes wrong next month?

  1. Explanation for A

    ✓ Correct

    Correct: the date rule is only true when the request is made, so it must not run before edits. See validators.

  2. Explanation for B

    ✗ Incorrect

    Not this one: when it runs is chosen when it is attached, and here edits were chosen too. See validators.

  3. Explanation for C

    ✗ Incorrect

    Not this one: a validator only refuses saves; it never changes records. See validators.

Check your answer

The correct answer is A. Open the explanation under each option to see why.

PracticeChoose one answer.

A validator returns { "success": false, "errors": [{ "errorCode": "TOO_LONG" }] }, and people see the text TOO_LONG instead of a sentence. What is missing?

  1. Explanation for A

    ✗ Incorrect

    Not this one: the function returns codes; the sentences are kept on the platform side. See validators.

  2. Explanation for B

    ✓ Correct

    Correct: each code is looked up in the Errors list to show its message. See validators.

  3. Explanation for C

    ✗ Incorrect

    Not this one: both kinds look their codes up the same way. See validators.

Check your answer

The correct answer is B. Open the explanation under each option to see why.

PracticeChoose one answer.

A record must never be saved with an end date before its start date, whether it comes from the form, a reaction or an outside system over the API. Which tool guarantees it?

  1. Explanation for A

    ✗ Incorrect

    Not this one: a lock stops edits to a field; it does not compare two values or refuse a save. See choosing the tool.

  2. Explanation for B

    ✗ Incorrect

    Not this one: it acts after the bad record is already stored. See choosing the tool.

  3. Explanation for C

    ✓ Correct

    Correct: it runs on the server before the save, whoever is saving. See choosing the tool.

Check your answer

The correct answer is C. Open the explanation under each option to see why.

PracticeChoose every answer that applies.

Which of these are good reasons to write a Function rather than an expression? Choose all that apply.

  1. Explanation for A

    ✓ Correct

    Correct: an expression cannot call outside systems; a Function can. See choosing the tool.

  2. Explanation for B

    ✓ Correct

    Correct: versioned, tested code with one owner suits a volatile rule table. See choosing the tool.

  3. Explanation for C

    ✗ Incorrect

    Not this one: arithmetic on the record’s own values is exactly the expression’s job. See choosing the tool.

  4. Explanation for D

    ✗ Incorrect

    Not this one: a Function adds a network call and a deployment; it is chosen for what it can do, not for speed. See choosing the tool.

Check your answer

The correct answers are A and B. Open the explanation under each option to see why.

You wrote a validator that guards data from every entry point, attached it at the right moment, and can choose among five tools for any rule. After Module 4 you can write deep code where the designer stops: deploy Functions that calculate, act and validate, and say what each kind guarantees.

Next. Module 5 turns the platform inside out: instead of your code running inside it, outside programs talk to it over its HTTP API.