---
title: Schemas and validation
project: Total.js V5
version: 0.0.20
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/json-schemas/
updated: 2026-11-18T16:57:24.576Z
---

# Schemas and validation

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

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](../../guides/json-schemas/).

## API

### NEWSCHEMA(name, schema)

Type: `method`

Registers an inline schema under a name.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name of the schema; a leading `@` is ignored. |
| `schema` | `String|Function` | yes |  | 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](../../guides/actions/).

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

NEWACTION('Customers/save', {
	input: '@Customer',
	action: function($, model) {
		$.success();
	}
});
```

Example: Actions in a schema
```js
NEWSCHEMA('Orders', function(schema) {
	schema.action('list', {
		query: 'page:Number',
		action: function($) {
			$.callback([]);
		}
	});
});
// creates the action "Orders/list"
```

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

Type: `method`

Parses an inline schema into a JSON schema object.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | no |  | Stores the schema in `F.jsonschemas` under this name and uses it in `$id`. |
| `url` | `String` | no | `CONF.url` | The base URL of `$id`. |

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.

Example: Parse and validate
```js
var schema = '*name:String(50),email:Email,age:Number'.toJSONSchema();
var result = schema.transform({ name: 'Peter', email: 'peter@example.com' });
console.log(result.response);
```

Example: Register under a name
```js
'*street:String,*city:String'.toJSONSchema('Address');
// F.jsonschemas.Address exists now
```

### F.newjsonschema(name, [schema])

Type: `method`

Registers a JSON schema or an inline schema.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String|Object` | yes |  | The name of the schema, an inline schema, or a JSON schema object with `$id`. |
| `schema` | `Object|String` | no |  | 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.

Example: A JSON schema object
```js
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' });
```

Example: An inline schema
```js
F.newjsonschema('Contact', '*name:String,*email:Email');
```

### F.jsonschemas

Type: `property`

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.

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

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

### jsonschemas/*.json

Type: `config`

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`.

Example: jsonschemas/Address.json
```js
{
	"$id": "Address",
	"type": "object",
	"properties": {
		"street": { "type": "string" },
		"city": { "type": "string" },
		"zip": { "type": "string", "subtype": "zip" }
	},
	"required": ["street", "city"]
}
```

Example: Use it
```js
NEWACTION('Addresses/create', {
	input: '@Address',
	action: function($, model) {
		$.success();
	}
});
```

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

Type: `method`

Validates and converts a value.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Object` | yes |  | The value to validate. |
| `partial` | `Boolean` | no | `false` | Validates only the fields that exist in the value. |
| `error` | `ErrorBuilder` | no | `new ErrorBuilder()` | A builder that receives the errors. |
| `path` | `String` | no |  | 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.

Example: Validate a body
```js
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);
```

Example: Partial update
```js
var schema = '*name:String,*email:Email,age:Number'.toJSONSchema();
var result = schema.transform({ age: 40 }, true);
// result.response === { age: 40 }, result.error === null
```

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

Type: `method`

Validates a value and throws on the first error.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Object` | yes |  | The value to validate. |
| `partial` | `Boolean` | no | `false` | Validates only the fields that exist in the value. |
| `path` | `String` | no |  | 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.

Example: Throw on invalid data
```js
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
}
```

### schema.toAITool(name)

Type: `method`

Creates an AI tool definition from an inline schema.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | 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](../../guides/ai-models/).

Example: A tool from a schema
```js
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
//		 }
//	 }
// }
```

### schema.toAIObject(name, [description])

Type: `method`

Converts an inline schema into a named JSON Schema object for AI models.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name of the object. |
| `description` | `String` | no |  | 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.

Example: A structured answer
```js
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']
// }
```

### *name:Type  or  !name:Type

Type: `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 `*`.

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

### name:Type // Message

Type: `type`

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`.

Example: Custom messages
```js
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', ... }]
```

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

Type: `type`

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`.

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

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

Type: `type`

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.

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

### name:SmallInt

Type: `type`

A number from -32767 to 32767.

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

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

### name:TinyInt

Type: `type`

A number from 0 to 255.

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

Example: TinyInt
```js
'level:TinyInt'.toJSONSchema().transform({ level: '12' }).response;
// { level: 12 }
```

### name:Boolean  name:Bool

Type: `type`

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`.

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

### name:Date

Type: `type`

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`.

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

### name:Email

Type: `type`

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.

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

### name:Email2

Type: `type`

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'`.

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

### name:Phone

Type: `type`

A phone number.

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

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

### name:URL

Type: `type`

A URL address.

Trimmed and checked with `String.isURL()`.

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

### name:Zip

Type: `type`

A ZIP code.

Trimmed and checked with `String.isZIP()`.

Example: Zip
```js
'zip:Zip'.toJSONSchema().transform({ zip: '12345' }).response;
```

### name:UID

Type: `type`

A Total.js unique identifier.

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

Example: UID
```js
'*id:UID'.toJSONSchema().transform({ id: UID() }).response;
```

### name:GUID

Type: `type`

A GUID.

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

Example: GUID
```js
'token:GUID'.toJSONSchema().transform({ token: GUID() }).response;
```

### name:Name

Type: `type`

A person name.

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

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

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

Type: `type`

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.

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

### name:Capitalize  name:Capitalize2

Type: `type`

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.

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

### name:Color

Type: `type`

A hex color.

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

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

### name:Icon

Type: `type`

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`.

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

### name:Base64

Type: `type`

A Base64 string.

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

Example: Base64
```js
'file:Base64'.toJSONSchema().transform({ file: 'SGVsbG8=' }).response;
```

### name:JSON

Type: `type`

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`.

Example: JSON
```js
'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' }]
```

### name:DataURI

Type: `type`

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`.

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

### name:IP

Type: `type`

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`.

Example: IP
```js
'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' }]
```

### name:DataURI2

Type: `type`

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`.

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

### name:SafeString

Type: `type`

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.

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

### name:Search

Type: `type`

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.

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

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

Type: `type`

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.

Example: Inline enum
```js
'*status:{draft|published|archived}'.toJSONSchema().transform({ status: 'published' }).response;
```

Example: JSON schema enum
```js
F.newjsonschema({
	$id: 'Task',
	type: 'object',
	properties: {
		priority: { type: 'string', enum: ['low', 'normal', 'high'] }
	}
});
```

### name:[Type]

Type: `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`.

Example: Arrays
```js
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 }] }
```

### name:{field:Type,...}

Type: `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}}}`.

Example: Nested object
```js
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' }
```

### name:@Schema  name:[@Schema]

Type: `type`

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.

Example: Reuse a schema
```js
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 }
```

### required: ['field', ...]

Type: `property`

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.

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

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

Type: `property`

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`.

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

### { type: 'string', nullable: true }

Type: `property`

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.

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

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

Type: `property`

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`.

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

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

Type: `property`

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.

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

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

Type: `property`

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.

Example: Array of tags
```js
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'] }
```

Example: Array of objects
```js
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
```

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

Type: `property`

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`.

Example: Local and registered references
```js
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' } } }
	}
});
```

### new ErrorBuilder()

Type: `class`

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).

Example: Collect errors
```js
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());
```

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

Type: `method`

Adds an error message or an HTTP status.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `error` | `String|Number` | yes |  | A message or an HTTP status code. |
| `path` | `String` | no |  | The path of the field. |
| `index` | `Number` | no |  | 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)')`.

Example: Messages and statuses
```js
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' }]
```

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

Type: `method`

Adds an error of a field, with an optional message.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name of the field. |
| `path` | `String` | no |  | The path of the field. |
| `index` | `Number` | no |  | 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])`.

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

### err.output([language])

Type: `method`

Returns the errors as an array of objects.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `language` | `String` | no | `'default'` | The language for resources and translations. |

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.

Example: Output
```js
var err = new ErrorBuilder();
err.push2('name');
console.log(err.output('en'));
```

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

Type: `method`

Returns the messages as one text.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `language` | `String` | no | `'default'` | The language. |
| `divider` | `String` | no | `'\n'` | The text between messages. |

Returns: `String`

The messages of `output(language)` joined by `divider`.

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

### err.reject([language])

Type: `method`

Returns the errors as an Error object.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `language` | `String` | no | `'default'` | The language. |

Returns: `Error`

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

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

### err.throw()

Type: `method`

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.

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

### err.replace(search, value)

Type: `method`

Replaces a text in all messages.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `search` | `String` | yes |  | The text to find. |
| `value` | `String` | yes |  | 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.

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

### ErrorBuilder.assign(value)

Type: `method`

Creates a builder from an error output, a message or an Error.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Array|String|Number|Error` | yes |  | 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.

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

### ErrorBuilder.transform(callback)

Type: `method`

Sets a global handler that changes the output of every ErrorBuilder.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function` | yes |  | `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.

Example: A custom error format
```js
ErrorBuilder.transform(function(output, language) {
	return { success: false, errors: output };
});
```
