Drive fields from a screen config
Map the rules that a screen config sets for a field onto the options of formatters and validators.
Before you begin
- Read Format and validate a form field.
- Know your config's keys for the field's rules.
The package doesn't read screen configs. Your service reads the config, and the package supplies the rules that the config points to.
Map a config field
This example uses a field described like this:
{ "field": "delivery_pin", "label": "Delivery PIN", "required": true,
"formatPattern": "numbersOnly",
"validation": { "pattern": "pincode", "message": "Delivery PIN must be 6 digits" } }
-
While the user types, pass the config's format name to
formatters:const shown = formatters(raw, field.formatPattern); -
When you check the field, map the config's keys onto the
validatorsoptions:const rules = field.validation || {};
const result = validators(value, rules.pattern || (field.type === "number" ? "number" : null), {
required: field.required,
label: field.label,
message: rules.message,
decimalPlaces: rules.decimalPlaces,
minValue: rules.min,
maxValue: rules.max,
minLength: rules.minLength,
maxLength: rules.maxLength,
});
// { valid: true } or { valid: false, code, message }
An option left undefined counts as not given.
A config field with no min passes minValue: undefined, and the package skips that check.
The same config works in a Python service, because rule names and results are the same in both languages.
What stays with your service
Conditions such as showIf and required_if stay with your service.
Decide whether a field is shown or required first, and then pass required to validators.