Schemas and validation
Inline schemas, JSON schemas and ErrorBuilder: how Total.js 5 validates and converts data.
Total.js 5 validates data with schemas. A schema describes the fields of an object, converts every value to its type and collects the errors. The same schema object works in actions, in your own code and in the files of the jsonschemas/ folder.
You can write a schema in two ways:
- an inline schema, a short string such as
'*name:String,email:Email,age:Number'; - a JSON schema, a plain object with
type,properties,requiredand other keywords.
An inline schema is turned into a JSON schema object, so both ways end in the same format and the same validator.
Inline schemas
An inline schema is a list of fields separated by commas or new lines. Each field is name:Type. Spaces around names and types are ignored and the type names are not case-sensitive (Email, email and EMAIL are the same). A field without a type is a String, and an unknown type is a String too.
var schema = '*name:String,*email:Email,age:Number,newsletter:Boolean'.toJSONSchema();
var result = schema.transform({ name: ' Peter ', email: 'PETER@EXAMPLE.COM', age: '33' });
// result.error === null
// result.response === { name: 'Peter', email: 'peter@example.com', age: 33, newsletter: false }transform() returns an object with two keys: response (the clean object) and error (an ErrorBuilder with the errors, or null). Only the fields of the schema are copied to the response; other keys of the input are dropped.
Modifiers
| Syntax | Meaning |
|---|---|
*name:String | The field is required (!name:String is the same) |
name:String(50) | The text can have at most 50 characters |
tags:[String] | An array of values of the type |
type:{draft|published} | The value must be one of the listed values |
address:{street:String,city:String} | A nested object with its own fields |
address:@Address | A nested object validated by the registered schema Address |
name:String // Enter your name | A custom error message for the field |
A required field fails when its value is empty: an empty string, a missing number, a missing boolean or a date that can't be parsed. 0 is a valid required number and false is a valid required boolean.
Types
| Type | What it does with the value |
|---|---|
String, Text | Converted to a string and trimmed |
String2 | Like String, but an empty value becomes null |
Number, Number2, Int, Integer, Float, Decimal | Parsed as a number ('1,5' gives 1.5); a value that is not a number is left out |
SmallInt | A number from -32767 to 32767 |
TinyInt | A number from 0 to 255 |
Boolean, Bool | true or false; strings like 'true', '1' or 'on' are parsed |
Date | A Date object, or null |
Email | Spaces removed, lower case, must be a valid email |
Email2 | Like Email, and the tag is removed: name+tag@domain.com gives name@domain.com |
Phone | Spaces removed, must be a valid phone number |
URL | Must be a valid URL |
Zip | Must be a valid ZIP code |
UID, GUID | Must be a valid Total.js UID or a GUID; empty becomes null |
Name | Formatted as a person name ('peter sirka' gives 'Peter Sirka') |
Lower, Lowercase, Upper, Uppercase | Converted to lower or upper case |
Capitalize, Capitalize2 | First letter of every word, or only of the first word, in upper case |
Color | A hex color: #RGB, #RRGGBB or #RRGGBBAA |
Icon | An icon class such as ti ti-home or fa fa-check |
Base64 | Must be a Base64 string; empty becomes null |
JSON | A string that looks like JSON (see String.isJSON()); it is kept as text and empty becomes null |
IP | An IPv4 or IPv6 address; trimmed, empty becomes null |
DataURI | Must be a Base64 data URI; parsed into { type, buffer } |
DataURI2 | Must be a Base64 data URI; kept as the original text |
SafeString | Rejected when it contains XSS or SQL injection patterns |
Search | Converted to a search string with String.toSearch() |
Strings, booleans and dates are always present in the response: a missing string is '', a missing boolean is false and a missing date is null. A missing number is left out.
var schema = 'color:Color,icon:Icon,photo:DataURI,avatar:DataURI2'.toJSONSchema();
var result = schema.transform({ color: '#FF0000', icon: 'ti ti-user', photo: 'data:image/png;base64,iVBORw0KGgo=', avatar: 'data:image/png;base64,iVBORw0KGgo=' });
// result.response.photo === { type: 'image/png', buffer: <Buffer> }
// result.response.avatar === 'data:image/png;base64,iVBORw0KGgo='Enums, arrays and nested objects
var schema = `*title:String(100)
status:{draft|published|archived}
tags:[String]
ratings:[Number]
author:{name:String,email:Email}
items:[{name:String,price:Number}]`.toJSONSchema();An enum accepts | or ; between the values. An array field accepts only an array; every item is converted to the type. [{...}] is an array of nested objects. A nested object can contain further nested objects and arrays, at any depth:
var schema = 'order:{number:String,lines:[{sku:String,qty:Number}],shipping:{address:{street:String,city:String}}}'.toJSONSchema();The errors of a nested field have a path such as author.email, items[1].price or order.shipping.address.city.
Registered schemas
NEWSCHEMA(name, schema) registers an inline schema under a name. Other schemas and actions use it with @name.
NEWSCHEMA('@Address', '*street:String,*city:String,zip:Zip');
NEWSCHEMA('@Customer', `*name:String(50)
*email:Email
address:@Address
branches:[@Address]`);All registered schemas are in the F.jsonschemas object. '...'.toJSONSchema(name) registers the schema under name too.
Schemas in actions
The input, output, query and params options of an action take an inline schema or the name of a registered schema with @. The input is validated before the action runs; when it fails, the action does not run and the client receives the errors. See Actions.
NEWACTION('Customers/create', {
input: '@Customer',
action: function($, model) {
// model is the validated object
$.success();
}
});
NEWACTION('Customers/list', {
query: 'page:Number,limit:Number,search:Search',
action: function($) {
// $.query.page is a number
$.callback([]);
}
});Errors from query have names that start with query. and errors from params start with params.. An action with partial: true validates only the fields that exist in the input, so it fits updates of a few fields.
JSON schemas
A JSON schema is an object. Register it with F.newjsonschema(), or put it in the jsonschemas/ folder.
F.newjsonschema({
$id: 'Product',
type: 'object',
properties: {
name: { type: 'string', maxLength: 100 },
sku: { type: 'string', subtype: 'uid' },
price: { type: 'number', minimum: 1 },
stock: { type: 'number', subtype: 'smallint' },
tags: { type: 'array', items: { type: 'string' }, uniqueItems: true },
supplier: { type: 'object', $ref: '#/definitions/Supplier' }
},
required: ['name', 'price'],
definitions: {
Supplier: {
type: 'object',
properties: { name: { type: 'string' }, email: { type: 'string', subtype: 'email' } },
required: ['name']
}
}
});
var result = F.jsonschemas.Product.transform({ name: 'Mug', price: '9.90' });Supported types: object, array, string, number (or integer), boolean (or bool) and date. Supported keywords: properties, required, minLength, maxLength, enum, minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, items, minItems, uniqueItems, $ref, definitions, and two Total.js keywords: subtype (a type from the inline table, such as email, uid, ip or json, plus ipaddress, the same as ip) and nullable (an empty string becomes null).
The jsonschemas folder
When the application starts, every .json file in jsonschemas/ is parsed and registered with the file name as its name. The folder is loaded before the folders with code, so jsonschemas/Address.json can be used as @Address in any action.
Errors and ErrorBuilder
ErrorBuilder collects errors. Validation fills it, and you can use it on your own.
var err = new ErrorBuilder();
err.push('The order is closed');
err.push2('email'); // a field error
err.output();
// [{ error: 'The order is closed' }, { name: 'email', error: 'The field "email" is invalid' }]The message of a field error is found in this order: the // message of the schema, a resource with the field name (see Localization), and the text The field "name" is invalid. A pushed number from 400 up sets the HTTP status (err.push(404)); otherwise the status is 400. When an action or a controller answers with an ErrorBuilder, the client receives the JSON array of output() with that status.
AI tools
Two methods of an inline schema describe it for AI models: the fields become the parameters, the // messages become their descriptions and the required fields stay required. See AI models.
schema.toAITool(name) returns a tool definition in the common function format:
var schema = '*city:String // The name of the city,days:Number // Number of days'.toJSONSchema();
var tool = schema.toAITool('weather');
// { type: 'function', function: { name: 'weather', parameters: { type: 'object', properties: {...}, required: ['city'] } } }schema.toAIObject(name, [description]) returns a standard JSON Schema object with a name, for example for a structured answer of a model. Dates get format: 'date-time', emails format: 'email', enums their values, and fields that can be null the type ['string', 'null']:
var schema = '*city:String // The name of the city,days:Number // Number of days'.toJSONSchema();
var obj = schema.toAIObject('forecast', 'The weather forecast for a city');
// { name: 'forecast', description: 'The weather forecast for a city', type: 'object', additionalProperties: false,
// properties: { city: { type: 'string', description: 'The name of the city' }, days: {...} }, required: ['city'] }