M4-S2 — Validators, interceptors, and choosing the right tool
Section titled “M4-S2 — Validators, interceptors, and choosing the right tool”| Module | M4 — Functions: code where the designer stops |
| After this session you can | Stop bad data at the door with your own rules, and choose the right tool for any rule a suite needs. |
| Time | Facilitated: 48 min · On your own: 48 min |
| Before you start | M4-S1: you can build, test and deploy a Function. The public Job Application form, reachable from Available jobs in a private window. |
| Go deeper | Validators · 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”Validators
Section titled “Validators”| Standalone Validator | Value Validator | |
|---|---|---|
| Checks | The whole record | One field’s value |
| Receives | { dataEntry, existingEntry } | { value } |
| Runs | Before the record is saved, edited or archived: you choose which when you attach it | When the record is saved |
| A refusal shows | The messages for the error codes it returned | The 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.
Interceptors
Section titled “Interceptors”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.
Choosing the tool
Section titled “Choosing the tool”| The rule | Tool | What it guarantees |
|---|---|---|
| Do something after an event | Reaction | Runs in the background; failures are logged, not shown |
| A value from the record’s own fields | Expression | Live in the form and on save; quietly wrong if mistyped |
| Logic the designer cannot hold, a rule table, an outside call | Function via Execute Function | Your code, versioned and tested; runs after the event |
| Refuse bad data before it is stored | Validator Function | Nothing invalid is saved, from the form, a reaction or the API |
| Reshape or answer a request before it is handled | Interceptor Function | Convenience 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
-
Copy your M4-S1 project as
application-check(cp -r offer-package application-check), go into it, and deleteparams.yaml(a validator takes no parameters). Infunc.yamlandpackage.json, change the name toapplication-check. -
Replace
src/index.tswith: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 passedconst 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 onlyconst 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 }; -
Run
npm install,npm run buildandnpm 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"}}}' | jqcurl -s -X POST http://localhost:8080 -H 'Content-Type: application/json' \-d '{"dataEntry": {"value": {"available_from": "2099-01-01", "expected_salary": "9000"}}}' | jqThe first answers two errors; the second
{"success": true}. -
Stop it and package it:
zip -r ../application-check.zip . -x 'node_modules/*' 'build/*'.
Deploy and attach it
- In Administration › Applications › Functions, select Add Function: Name application-check, Type Standalone Validator, Function Scope Entity, Job Application; upload the ZIP.
- 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. - 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
- 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. - Correct the date to next month and the salary to 9000, and submit: the application is accepted.
- 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 see | What to do |
|---|---|
| The form shows a code, not your message | The code under Errors does not match the code the function returns, letter for letter. |
| Every application is refused | Test locally with a valid record: a date compared as a date object instead of a string, or a missing ?? {}, refuses everything. |
| Nothing is refused | The validator is not attached, is attached to edits only, or is not Provisioned. |
| HR’s edits are refused | It 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”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?
Check your answer
The correct answer is B. Open the explanation under each option to see why.
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?
Check your answer
The correct answer is A. Open the explanation under each option to see why.
A validator returns { "success": false, "errors": [{ "errorCode": "TOO_LONG" }] }, and people see
the text TOO_LONG instead of a sentence. What is missing?
Check your answer
The correct answer is B. Open the explanation under each option to see why.
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?
Check your answer
The correct answer is C. Open the explanation under each option to see why.
Which of these are good reasons to write a Function rather than an expression? Choose all that apply.
Check your answer
The correct answers are A and B. Open the explanation under each option to see why.
↺ Recap (1 min) — After Module 4
Section titled “↺ Recap (1 min) — After Module 4”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.