Spanish Total.js
English
Documentation For AI agents
Contents

Schemas and validation

Inline schema types and modifiers, JSON schema keywords, schema methods and ErrorBuilder.

.md GitHub
On this page

The types and modifiers of inline schemas, the keywords of JSON schemas, the methods to register and run schemas, and the ErrorBuilder class. For an introduction with examples, read Schemas and validation.

API

method

NEWSCHEMA(name, schema)

Registers an inline schema under a name.
ParameterTypeDescription
name String The name of the schema; a leading @ is ignored.
schema String|Function An inline schema, or a function that defines actions.

Returns Object The JSON schema object when schema is a string.

With a string, the inline schema is parsed and stored in F.jsonschemas[name]. A leading @ in the name is removed, so '@Address' and 'Address' register the same name. Other schemas and actions use it as @Address.

With a function, the function receives an object with name, actions and action(name, meta). action() creates an action called <schema name>/<action name> with NEWACTION.

Register and use a schema
NEWSCHEMA('@Address', '*street:String,*city:String,zip:Zip');
NEWSCHEMA('@Customer', '*name:String,address:@Address');

NEWACTION('Customers/save', {
	input: '@Customer',
	action: function($, model) {
		$.success();
	}
});
Actions in a schema
NEWSCHEMA('Orders', function(schema) {
	schema.action('list', {
		query: 'page:Number',
		action: function($) {
			$.callback([]);
		}
	});
});
// creates the action "Orders/list"
method

'...'.toJSONSchema([name], [url])

Parses an inline schema into a JSON schema object.
ParameterTypeDescription
name? String Stores the schema in F.jsonschemas under this name and uses it in $id.
url? String The base URL of $id. Default: CONF.url

Returns Object A JSON schema object.

Returns an object with $id, $schema, type: 'object', properties, required, errors (the // messages) and the methods transform() and validate(). With name, the schema is also stored in F.jsonschemas[name].

The $id is url + name + '.json'. Without url, CONF.url is used, or https://schemas.totaljs.com/. Without name, a hash of the string is used. String.parseSchema() is the same method.

Parse and validate
var schema = '*name:String(50),email:Email,age:Number'.toJSONSchema();
var result = schema.transform({ name: 'Peter', email: 'peter@example.com' });
console.log(result.response);
Register under a name
'*street:String,*city:String'.toJSONSchema('Address');
// F.jsonschemas.Address exists now
method

F.newjsonschema(name, [schema])

Registers a JSON schema or an inline schema.
ParameterTypeDescription
name String|Object The name of the schema, an inline schema, or a JSON schema object with $id.
schema? Object|String A JSON schema object or an inline schema.

Returns Object The registered schema.

The schema is stored in F.jsonschemas under the name and under its $id, and gets the transform() method. The forms:

  • F.newjsonschema(object): a JSON schema object; its $id is the name.
  • F.newjsonschema(name, object): a JSON schema object under name.
  • F.newjsonschema(name, 'inline schema'): an inline schema; $id is set to name.
  • F.newjsonschema('inline schema'): an inline schema registered under its generated $id.

The files of the jsonschemas/ folder are registered with this method.

A JSON schema object
F.newjsonschema({
	$id: 'Product',
	type: 'object',
	properties: {
		name: { type: 'string', maxLength: 100 },
		price: { type: 'number', minimum: 1 }
	},
	required: ['name']
});

var result = F.jsonschemas.Product.transform({ name: 'Mug', price: '9.90' });
An inline schema
F.newjsonschema('Contact', '*name:String,*email:Email');
property

F.jsonschemas

All registered schemas by name.

Returns Object

An object of every schema registered by NEWSCHEMA(), F.newjsonschema(), toJSONSchema(name) and the jsonschemas/ folder. @name in inline schemas and actions, and $ref in JSON schemas, look up schemas here.

Validate with a registered schema
NEWSCHEMA('@Contact', '*name:String,*email:Email');

var result = F.jsonschemas.Contact.transform({ name: 'Peter', email: 'bad' });
if (result.error)
	console.log(result.error.output());
config

jsonschemas/*.json

A folder of schemas loaded when the application starts.

Every .json file is parsed and registered with F.newjsonschema(); the file name without the extension is the name of the schema. The folder is loaded before the folders with code, so actions can use its schemas with @name.

jsonschemas/Address.json
{
	"$id": "Address",
	"type": "object",
	"properties": {
		"street": { "type": "string" },
		"city": { "type": "string" },
		"zip": { "type": "string", "subtype": "zip" }
	},
	"required": ["street", "city"]
}
Use it
NEWACTION('Addresses/create', {
	input: '@Address',
	action: function($, model) {
		$.success();
	}
});
method

schema.transform(value, [partial], [error], [path])

Validates and converts a value.
ParameterTypeDescription
value Object The value to validate.
partial? Boolean Validates only the fields that exist in the value. Default: false
error? ErrorBuilder A builder that receives the errors. Default: new ErrorBuilder()
path? String A path prefix for the error paths.

Returns Object { error: ErrorBuilder|null, response: Object }

Returns { error, response }. response is the converted value: for an object schema, a new object with only the fields of the schema, or undefined when no field has a value. error is an ErrorBuilder with the errors, or null when there are none.

With partial, fields that are undefined in the value are skipped, so missing required fields do not fail. Pass your own ErrorBuilder as error to collect errors of several validations in one builder.

Validate a body
var schema = '*name:String,*email:Email'.toJSONSchema();
var result = schema.transform({ name: 'Peter', email: 'wrong' });

if (result.error)
	console.log(result.error.output());
	// [{ name: 'email', error: 'The field "email" is invalid', path: 'email' }]
else
	console.log(result.response);
Partial update
var schema = '*name:String,*email:Email,age:Number'.toJSONSchema();
var result = schema.transform({ age: 40 }, true);
// result.response === { age: 40 }, result.error === null
method

schema.validate(value, [partial], [path])

Validates a value and throws on the first error.
ParameterTypeDescription
value Object The value to validate.
partial? Boolean Validates only the fields that exist in the value. Default: false
path? String A path prefix for the error paths.

Returns Object The converted value.

Returns the converted value. When the value is not valid, it throws an Error with the message of the first error. Use it where an exception is simpler than checking result.error. Only schemas made from an inline schema have this method.

Throw on invalid data
var schema = '*name:String,*email:Email'.toJSONSchema();

try {
	var model = schema.validate({ name: 'Peter' });
} catch (e) {
	console.log(e.message); // The field "email" is invalid
}
method

schema.toAITool(name)

Creates an AI tool definition from an inline schema.
ParameterTypeDescription
name String The name of the tool.

Returns Object The tool definition.

Returns a function-tool object for AI models. Each field becomes a parameter with its type and, as its description, the // message of the field (an empty string without one). The required fields of the schema are the required parameters. The description of the tool is schema.summary or schema.description when you set one. It exists on schemas made from an inline schema (toJSONSchema(), NEWSCHEMA()), not on JSON schema objects registered with F.newjsonschema(). See AI models.

A tool from a schema
var schema = '*city:String // The name of the city,days:Number // Number of days'.toJSONSchema();
schema.description = 'Returns the weather forecast';

var tool = schema.toAITool('weather');
// {
//	 type: 'function',
//	 function: {
//		 name: 'weather',
//		 description: 'Returns the weather forecast',
//		 parameters: {
//			 type: 'object',
//			 properties: {
//				 city: { type: 'string', description: 'The name of the city' },
//				 days: { type: 'number', description: 'Number of days' }
//			 },
//			 required: ['city'],
//			 additionalProperties: false
//		 }
//	 }
// }
method

schema.toAIObject(name, [description])

Converts an inline schema into a named JSON Schema object for AI models.
ParameterTypeDescription
name String The name of the object.
description? String A description of the object.

Returns Object The JSON Schema object.

Returns { name, description, type: 'object', properties, required, additionalProperties: false }. The properties use standard JSON Schema: Date is { type: 'string', format: 'date-time' }, Email has format: 'email', an enum has enum, an array has items, and a type that can be null (such as String2, UID, GUID, JSON, IP or Base64) is ['string', 'null']. The // message of a field is its description. required is left out when no field is required. Like toAITool(), it exists on schemas made from an inline schema.

A structured answer
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',
//	 properties: {
//		 city: { type: 'string', description: 'The name of the city' },
//		 days: { type: 'number', description: 'Number of days' }
//	 },
//	 type: 'object',
//	 additionalProperties: false,
//	 required: ['city']
// }
type

*name:Type or !name:Type

Marks a field of an inline schema as required.

A required field fails when its value is empty. For strings that is an empty value before trimming (a text of only spaces passes and becomes ''); for numbers a missing or non-numeric value (0 passes); for booleans a missing value (false passes); for dates a value that can't be parsed; for arrays an empty array or a value that is not an array. A required nested object ({...} or @name) does not fail when it is missing. ! is the same as *.

Required fields
var schema = '*name:String,*email:Email,phone:Phone'.toJSONSchema();
var result = schema.transform({ name: '' });
// errors for "name" and "email"
type

name:Type // Message

Sets a custom error message for a field of an inline schema.

The text after // is the error message of the field. Because commas separate fields, the message can't contain a comma; write the schema on several lines (one field per line) when the messages are long. The messages are stored in schema.errors.

Custom messages
var schema = `*name:String // Enter your name
	*email:Email // Enter a valid email address`.toJSONSchema();

var result = schema.transform({ email: 'x' });
console.log(result.error.output());
// [{ name: 'name', error: 'Enter your name', ... }, { name: 'email', error: 'Enter a valid email address', ... }]
type

name:String name:String(max) name:Text name:String2

Text values.

Any value is converted to a string, trimmed, and non-breaking spaces become normal spaces. A missing value is ''. String(50) sets the maximum length; a longer text is an error. The length is checked before trimming, so spaces around the text count. Text is the same as String. String2 turns an empty value into null.

Strings
var schema = '*title:String(100),note:Text,code:String2'.toJSONSchema();
schema.transform({ title: '  Hello  ', code: '' }).response;
// { title: 'Hello', note: '', code: null }
type

name:Number (Number2, Int, Integer, Float, Decimal)

Numeric values.

A number stays a number; a string with digits is parsed with String.parseFloat() ('33' gives 33, '1,5' gives 1.5). Other values are treated as missing and the field is left out of the response. Number2, Int, Integer, Float and Decimal are names of the same type.

Numbers
var schema = 'price:Number,count:Int'.toJSONSchema();
schema.transform({ price: '9,90', count: '3' }).response;
// { price: 9.9, count: 3 }
type

name:SmallInt

A number from -32767 to 32767.

Parsed like Number; a value outside the range is an error.

SmallInt
'priority:SmallInt'.toJSONSchema().transform({ priority: 40000 }).error.output();
// [{ name: 'priority', error: 'The field "priority" is invalid', path: 'priority' }]
type

name:TinyInt

A number from 0 to 255.

Parsed like Number; a value outside the range is an error.

TinyInt
'level:TinyInt'.toJSONSchema().transform({ level: '12' }).response;
// { level: 12 }
type

name:Boolean name:Bool

True or false.

A boolean stays as it is; other values are parsed with String.parseBoolean() ('true', '1', 'on' give true). The field is always in the response: a missing value is false.

Checkbox
'newsletter:Boolean,terms:Bool'.toJSONSchema().transform({ newsletter: 'on' }).response;
// { newsletter: true, terms: false }
type

name:Date

A date.

A Date stays as it is; other values are parsed with String.parseDate(). A value that can't be parsed, a missing value, or a date before 1 January 1970 is null.

Date
'birthday:Date'.toJSONSchema().transform({ birthday: '1990-05-20' }).response;
// { birthday: Date }
type

name:Email

An email address.

All whitespace is removed and the value is converted to lower case, then checked with String.isEmail(). An empty value is allowed unless the field is required.

Email
'*email:Email'.toJSONSchema().transform({ email: ' Peter@Example.COM ' }).response;
// { email: 'peter@example.com' }
type

name:Email2

An email address without its tag.

Works like Email and also removes the tag of the address: the part from + to @, so name+tag@domain.com becomes name@domain.com. Use it when one person must not register twice with tagged addresses. In JSON schemas it is subtype: 'email2'; toAIObject() and the MCP server describe it as format: 'email'.

Email2
'*email:Email2'.toJSONSchema().transform({ email: ' Peter+News@Example.COM ' }).response;
// { email: 'peter@example.com' }
type

name:Phone

A phone number.

Whitespace is removed, then the value is checked with String.isPhone().

Phone
'phone:Phone'.toJSONSchema().transform({ phone: '+421 900 123 456' }).response;
// { phone: '+421900123456' }
type

name:URL

A URL address.

Trimmed and checked with String.isURL().

URL
'website:URL'.toJSONSchema().transform({ website: 'https://www.totaljs.com' }).response;
type

name:Zip

A ZIP code.

Trimmed and checked with String.isZIP().

Zip
'zip:Zip'.toJSONSchema().transform({ zip: '12345' }).response;
type

name:UID

A Total.js unique identifier.

Trimmed and checked with String.isUID(), the format made by UID(). An empty value becomes null.

UID
'*id:UID'.toJSONSchema().transform({ id: UID() }).response;
type

name:GUID

A GUID.

Trimmed and checked with String.isGUID(). An empty value becomes null.

GUID
'token:GUID'.toJSONSchema().transform({ token: GUID() }).response;
type

name:Name

A person name.

The value is formatted with String.toName(): every word starts with an upper-case letter.

Name
'fullname:Name'.toJSONSchema().transform({ fullname: 'peter sirka' }).response;
// { fullname: 'Peter Sirka' }
type

name:Lower name:Lowercase name:Upper name:Uppercase

Text in lower or upper case.

Lower and Lowercase trim the value and convert it to lower case. Upper and Uppercase convert it to upper case.

Case
'login:Lower,country:Upper'.toJSONSchema().transform({ login: 'PETER', country: 'sk' }).response;
// { login: 'peter', country: 'SK' }
type

name:Capitalize name:Capitalize2

Text with capital letters.

Capitalize puts the first letter of every word in upper case. Capitalize2 puts only the first letter of the text in upper case.

Capitalize
'title:Capitalize,sentence:Capitalize2'.toJSONSchema().transform({ title: 'hello world', sentence: 'hello world' }).response;
// { title: 'Hello World', sentence: 'Hello world' }
type

name:Color

A hex color.

The value must be #RGB, #RRGGBB or #RRGGBBAA (letters in any case).

Color
'color:Color'.toJSONSchema().transform({ color: '#4285F4' }).response;
type

name:Icon

An icon class.

The value must be an icon class of Total.js icons or Font Awesome: a prefix (ti, tic, fa, far, fab, fad, fal, fas), a space, and the icon name with a ti-, tic- or fa- prefix, for example ti ti-home or fas fa-check.

Icon
'icon:Icon'.toJSONSchema().transform({ icon: 'ti ti-home' }).response;
type

name:Base64

A Base64 string.

Trimmed and checked with String.isBase64(). An empty value becomes null.

Base64
'file:Base64'.toJSONSchema().transform({ file: 'SGVsbG8=' }).response;
type

name:JSON

A JSON text.

Trimmed and checked with String.isJSON(): the value must start and end like a JSON object, array or string, or be a number. The content is not parsed and the value stays a string; parse it with String.parseJSON() when you need the object. An empty value becomes null.

JSON
'settings:JSON'.toJSONSchema().transform({ settings: '{"theme":"dark"}' }).response;
// { settings: '{"theme":"dark"}' }

'settings:JSON'.toJSONSchema().transform({ settings: 'dark' }).error.output();
// [{ name: 'settings', error: 'The field "settings" is invalid', path: 'settings' }]
type

name:DataURI

A data URI parsed into a buffer.

The value must be a Base64 data URI such as data:image/png;base64,.... It is parsed with String.parseDataURI() into { type, buffer }, where type is the content type and buffer the decoded data. An empty value becomes null.

Upload a photo as JSON
NEWACTION('Users/photo', {
	input: '*photo:DataURI',
	action: function($, model) {
		// model.photo.type === 'image/png'
		// model.photo.buffer is a Buffer
		$.success();
	}
});
type

name:IP

An IP address.

Trimmed and checked with Node.js net.isIP(): a canonical IPv4 address (10.0.0.1) or an IPv6 address (::1). A host name or a short form such as 127.1 is invalid. An empty value becomes null.

IP
'server:IP'.toJSONSchema().transform({ server: ' 10.0.0.1 ' }).response;
// { server: '10.0.0.1' }

'server:IP'.toJSONSchema().transform({ server: '10.0.0.300' }).error.output();
// [{ name: 'server', error: 'The field "server" is invalid', path: 'server' }]
type

name:DataURI2

A data URI kept as text.

The value must be a Base64 data URI, like DataURI, but it is not parsed: the response contains the original text. Use it when you store the data URI as it is. An empty value becomes null.

Keep the text
'avatar:DataURI2'.toJSONSchema().transform({ avatar: 'data:image/png;base64,iVBORw0KGgo=' }).response;
// { avatar: 'data:image/png;base64,iVBORw0KGgo=' }
type

name:SafeString

Text without XSS or SQL injection patterns.

Trimmed and rejected when String.isXSS() or String.isSQLInjection() finds a dangerous pattern, such as an HTML tag.

SafeString
'comment:SafeString'.toJSONSchema().transform({ comment: '<script>alert(1)</script>' }).error.output();
// [{ name: 'comment', error: 'The field "comment" is invalid', path: 'comment' }]
type

name:Search

A normalized search phrase.

Trimmed and converted with String.toSearch(): lower case, without diacritics and with simplified letters, so it can be compared with indexed search text.

Search
'q:Search'.toJSONSchema().transform({ q: 'Hello Wörld' }).response;
// { q: 'helo world' }
type

name:{a|b|c} or { type: 'string', enum: [...] }

A value from a fixed list.

In an inline schema, list the values in braces, separated by | or ;. In a JSON schema, use the enum keyword with an array. A value that is not in the list is an error; an empty value is allowed unless the field is required.

Inline enum
'*status:{draft|published|archived}'.toJSONSchema().transform({ status: 'published' }).response;
JSON schema enum
F.newjsonschema({
	$id: 'Task',
	type: 'object',
	properties: {
		priority: { type: 'string', enum: ['low', 'normal', 'high'] }
	}
});
type

name:[Type]

An array of values of one type.

The value must be an array; anything else leaves the field out (or fails when the field is required). Every item is converted to the type, for example [Number] turns ['1', 2] into [1, 2]. [{...}] is an array of nested objects and [@name] an array validated by a registered schema; the error paths contain the index, such as items[1].price.

Arrays
var schema = 'tags:[String],scores:[Number],lines:[{sku:String,qty:Number}]'.toJSONSchema();
schema.transform({ tags: ['a', ' b '], scores: ['1', 2], lines: [{ sku: 'A1', qty: '2' }] }).response;
// { tags: ['a', 'b'], scores: [1, 2], lines: [{ sku: 'A1', qty: 2 }] }
type

name:{field:Type,...}

A nested object.

Braces with fields (not an enum) make a nested object with its own fields, modifiers and types. The nested object is validated like the main one and its errors have paths such as address.city. A nested object can contain further nested objects and arrays, for example order:{lines:[{sku:String,qty:Number}],shipping:{address:{city:String}}}.

Nested object
var schema = '*name:String,address:{street:String,*city:String,zip:Zip}'.toJSONSchema();
var result = schema.transform({ name: 'Peter', address: { street: 'Main 1' } });
// error: { name: 'city', path: 'address.city' }
type

name:@Schema name:[@Schema]

A nested object validated by a registered schema.

The value is validated by the schema registered as Schema (with NEWSCHEMA(), F.newjsonschema() or the jsonschemas/ folder). [@Schema] validates every item of an array. The errors keep the paths of the nested object.

Reuse a schema
NEWSCHEMA('@Address', '*street:String,*city:String');
NEWSCHEMA('@Company', '*name:String,headquarters:@Address,branches:[@Address]');

var result = F.jsonschemas.Company.transform({ name: 'Acme', branches: [{ street: 'A 1', city: 'X' }, { street: 'B 2' }] });
// error: { name: 'city', path: 'branches[1].city', index: 1 }
property

required: ['field', ...]

The required fields of an object schema.

An array of property names. The rules for empty values are the same as for * in inline schemas.

required
F.newjsonschema({
	$id: 'Login',
	type: 'object',
	properties: {
		email: { type: 'string', subtype: 'email' },
		password: { type: 'string' }
	},
	required: ['email', 'password']
});
property

{ type: 'string', subtype: 'email' }

A Total.js keyword that selects a special conversion.

For string properties, subtype uses the conversion of an inline type: email, email2, phone, url, zip, uid, guid, name, lower, lowercase, upper, uppercase, capitalize, capitalize2, color, icon, base64, datauri, datauri2, safestring, search, json or ip. ipaddress is the same as ip and exists only in JSON schemas. For number properties, smallint and tinyint check the range. An empty string stays ''; add nullable: true to get null.

subtype
F.newjsonschema({
	$id: 'Server',
	type: 'object',
	properties: {
		host: { type: 'string', subtype: 'ip' },
		config: { type: 'string', subtype: 'json' },
		port: { type: 'number', subtype: 'smallint' }
	}
});
property

{ type: 'string', nullable: true }

A Total.js keyword that turns an empty string into null.

For a string property, an empty value becomes null instead of ''. Inline types String2, UID, GUID, Base64, DataURI and DataURI2 set it for you.

nullable
var schema = F.newjsonschema({ $id: 'Note', type: 'object', properties: { text: { type: 'string', nullable: true } } });
schema.transform({ text: '' }).response;
// { text: null }
property

{ type: 'string', minLength: 3, maxLength: 50 }

The length limits of a string.

minLength and maxLength check the number of characters of a string. String(50) in an inline schema sets maxLength.

Length
F.newjsonschema({
	$id: 'Nick',
	type: 'object',
	properties: { nick: { type: 'string', minLength: 3, maxLength: 20 } }
});
property

{ type: 'number', minimum: 1, maximum: 100 }

The limits of a number.

minimum and maximum are inclusive limits, exclusiveMinimum and exclusiveMaximum exclusive ones. multipleOf requires a value divisible by the given number.

Number limits
F.newjsonschema({
	$id: 'Order',
	type: 'object',
	properties: {
		quantity: { type: 'number', minimum: 1, maximum: 100 },
		discount: { type: 'number', exclusiveMaximum: 50 },
		pack: { type: 'number', multipleOf: 6 }
	}
});
property

{ type: 'array', items: { type: 'string' } }

The schema of the items of an array.

items is one schema for every item: a type with its keywords (string, number, boolean, date), an object with its own properties and required, or a $ref. Each item of an object is validated and converted like a nested object; an error of an item has the name and the path field.property and the position of the item in index. minItems sets the smallest number of items of a non-empty array; an empty array fails only when the field is required. uniqueItems: true removes duplicate values.

Array of tags
F.newjsonschema({
	$id: 'Article',
	type: 'object',
	properties: {
		tags: { type: 'array', items: { type: 'string' }, minItems: 1, uniqueItems: true }
	}
});

F.jsonschemas.Article.transform({ tags: ['a', 'b', 'a'] }).response;
// { tags: ['a', 'b'] }
Array of objects
F.newjsonschema({
	$id: 'Order',
	type: 'object',
	properties: {
		items: { type: 'array', items: { type: 'object', properties: { sku: { type: 'string' }, qty: { type: 'number' } }, required: ['qty'] } }
	}
});

var result = F.jsonschemas.Order.transform({ items: [{ sku: 'A', qty: '2' }, { sku: 'B' }] });
// result.error.items[0]: name 'items.qty', path 'items.qty', index 1
property

{ type: 'object', $ref: '#/definitions/Name' }

A reference to another schema.

$ref validates an object (or every item of an array, in items) by another schema. A value starting with #/ points to the definitions of the same schema, for example #/definitions/Address. Any other value is the name or $id of a schema registered in F.jsonschemas.

Local and registered references
F.newjsonschema({ $id: 'Address', type: 'object', properties: { city: { type: 'string' } }, required: ['city'] });

F.newjsonschema({
	$id: 'Invoice',
	type: 'object',
	properties: {
		billing: { type: 'object', $ref: 'Address' },
		lines: { type: 'array', items: { $ref: '#/definitions/Line' } }
	},
	definitions: {
		Line: { type: 'object', properties: { name: { type: 'string' }, price: { type: 'number' } } }
	}
});
class

new ErrorBuilder()

A list of errors with an HTTP status.

Returns ErrorBuilder

Validation returns its errors in an ErrorBuilder, and actions and controllers answer with it as a JSON array. You can create one to collect your own errors. Its properties: items (the raw errors), length (the number of errors), status (the HTTP status, 400 by default) and prefix (a text put before the names of field errors).

Collect errors
var err = new ErrorBuilder();

if (!model.email)
	err.push2('email');

if (model.age < 18)
	err.push('You must be 18 or older');

if (err.length)
	console.log(err.output());
method

err.push(error, [path], [index])

Adds an error message or an HTTP status.
ParameterTypeDescription
error String|Number A message or an HTTP status code.
path? String The path of the field.
index? Number The index of an array item.

Returns ErrorBuilder The same builder.

A number from 400 up sets status and adds the HTTP status text, for example 404 adds 404: Not Found. Any other value is added as the message. Without a value, 401 is pushed. A message that starts with @( is translated by output(), for example err.push('@(Access denied)').

Messages and statuses
var err = new ErrorBuilder();
err.push('The product is sold out');
err.push(409);
err.status;	 // 409
err.output();   // [{ error: 'The product is sold out' }, { error: '409: Conflict' }]
method

err.push2(name, [path], [index], [error])

Adds an error of a field, with an optional message.
ParameterTypeDescription
name String The name of the field.
path? String The path of the field.
index? Number The index of an array item.

Returns ErrorBuilder The same builder.

Adds an error for the field name (with prefix before it). Without error, the message is resolved by output(): first the // messages of the schema, then the resource with the field name in the language of the output, then The field "name" is invalid. With error, that text is the message.

Signature: err.push2(name, [path], [index], [error]).

Field error
var err = new ErrorBuilder();
err.push2('email', 'contact.email');
err.output();
// [{ name: 'email', error: 'The field "email" is invalid', path: 'contact.email' }]
method

err.output([language])

Returns the errors as an array of objects.
ParameterTypeDescription
language? String The language for resources and translations. Default: 'default'

Returns Array The list of errors.

Each item is { name, error, path, index } with the final message. Messages of field errors are read from the resources of language, @(...) texts are translated, and the replacements of replace() are applied. When a global ErrorBuilder.transform() handler exists, its result is returned instead.

Output
var err = new ErrorBuilder();
err.push2('name');
console.log(err.output('en'));
method

err.toString([language], [divider])

Returns the messages as one text.
ParameterTypeDescription
language? String The language. Default: 'default'
divider? String The text between messages. Default: '\n'

Returns String

The messages of output(language) joined by divider.

Text
var err = new ErrorBuilder();
err.push('First');
err.push('Second');
err.toString();			   // 'First\nSecond'
err.toString('default', ', '); // 'First, Second'
method

err.reject([language])

Returns the errors as an Error object.
ParameterTypeDescription
language? String The language. Default: 'default'

Returns Error

Creates new Error() with all messages joined without a divider. Useful to reject a promise.

Reject a promise
return new Promise(function(resolve, reject) {
	var err = new ErrorBuilder();
	err.push('Not allowed');
	reject(err.reject());
});
method

err.throw()

Makes the builder throw on the next error.

Returns ErrorBuilder The same builder.

After throw(), every push() or push2() throws an Error with the message of the first error. schema.validate() uses it.

Throw at once
var err = new ErrorBuilder().throw();
try {
	err.push('Invalid token');
} catch (e) {
	console.log(e.message); // Invalid token
}
method

err.replace(search, value)

Replaces a text in all messages.
ParameterTypeDescription
search String The text to find.
value String The new text.

Returns ErrorBuilder The same builder.

The replacement is applied by output() to every message, so you can push a message with a placeholder and fill it later.

Placeholder
var err = new ErrorBuilder();
err.push('The limit is {limit} items');
err.replace('{limit}', 10);
err.toString(); // 'The limit is 10 items'
method

ErrorBuilder.assign(value)

Creates a builder from an error output, a message or an Error.
ParameterTypeDescription
value Array|String|Number|Error The errors.

Returns ErrorBuilder A new builder.

With an array, every item that has error is added (for example the JSON errors returned by another Total.js app). A number or a string is pushed, and an Error is pushed as its text.

Errors from another service
var err = ErrorBuilder.assign([{ name: 'email', error: 'Email is taken' }]);
err.length; // 1
method

ErrorBuilder.transform(callback)

Sets a global handler that changes the output of every ErrorBuilder.
ParameterTypeDescription
callback Function function(output, language) that returns the new output.

callback(output, language) receives the array made by output() and returns what output() returns instead. Because actions and controllers send output() to the client, this changes the format of all error responses.

A custom error format
ErrorBuilder.transform(function(output, language) {
	return { success: false, errors: output };
});
Made in Europe