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

# Schemi e validazione

> Tipi e modificatori degli schemi inline, parole chiave degli schemi JSON, metodi degli schemi ed ErrorBuilder.

I tipi e i modificatori degli schemi inline, le parole chiave degli schemi JSON, i metodi per registrare ed eseguire gli schemi e la classe `ErrorBuilder`. Per un'introduzione con esempi, leggi [Schemi e validazione](../../guides/json-schemas/).

## API

### NEWSCHEMA(name, schema)

Type: `method`

Registra uno schema inline con un nome.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Il nome dello schema; un `@` iniziale viene ignorato. |
| `schema` | `String|Function` | yes |  | Uno schema inline, o una funzione che definisce azioni. |

Returns: `Object` L'oggetto schema JSON quando `schema` è una stringa.

Con una stringa, lo schema inline viene interpretato e salvato in `F.jsonschemas[name]`. Un `@` iniziale nel nome viene rimosso, quindi `'@Address'` e `'Address'` registrano lo stesso nome. Altri schemi e azioni lo usano come `@Address`.

Con una funzione, la funzione riceve un oggetto con `name`, `actions` e `action(name, meta)`. `action()` crea un'azione chiamata `<schema name>/<action name>` con [NEWACTION](../../guides/actions/).

Example: Registrare e usare uno 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: Azioni in uno 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`

Interpreta uno schema inline in un oggetto schema JSON.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | no |  | Salva lo schema in `F.jsonschemas` con questo nome e lo usa in `$id`. |
| `url` | `String` | no | `CONF.url` | L'URL di base di `$id`. |

Returns: `Object` Un oggetto schema JSON.

Restituisce un oggetto con `$id`, `$schema`, `type: 'object'`, `properties`, `required`, `errors` (i messaggi `//`) e i metodi `transform()` e `validate()`. Con `name`, lo schema viene anche salvato in `F.jsonschemas[name]`.

L'`$id` è `url + name + '.json'`. Senza `url`, viene usato `CONF.url`, oppure `https://schemas.totaljs.com/`. Senza `name`, viene usato un hash della stringa. `String.parseSchema()` è lo stesso metodo.

Example: Interpretare e validare
```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: Registrare con un nome
```js
'*street:String,*city:String'.toJSONSchema('Address');
// F.jsonschemas.Address exists now
```

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

Type: `method`

Registra uno schema JSON o uno schema inline.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String|Object` | yes |  | Il nome dello schema, uno schema inline, o un oggetto schema JSON con `$id`. |
| `schema` | `Object|String` | no |  | Un oggetto schema JSON o uno schema inline. |

Returns: `Object` Lo schema registrato.

Lo schema viene salvato in `F.jsonschemas` con il nome e con il suo `$id`, e riceve il metodo `transform()`. Le forme:

- `F.newjsonschema(object)`: un oggetto schema JSON; il suo `$id` è il nome.
- `F.newjsonschema(name, object)`: un oggetto schema JSON con il nome `name`.
- `F.newjsonschema(name, 'inline schema')`: uno schema inline; `$id` viene impostato a `name`.
- `F.newjsonschema('inline schema')`: uno schema inline registrato con il suo `$id` generato.

I file della cartella `jsonschemas/` vengono registrati con questo metodo.

Example: Un oggetto schema JSON
```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: Uno schema inline
```js
F.newjsonschema('Contact', '*name:String,*email:Email');
```

### F.jsonschemas

Type: `property`

Tutti gli schemi registrati, per nome.

Returns: `Object`

Un oggetto con ogni schema registrato da `NEWSCHEMA()`, `F.newjsonschema()`, `toJSONSchema(name)` e dalla cartella `jsonschemas/`. `@name` negli schemi inline e nelle azioni, e `$ref` negli schemi JSON, cercano gli schemi qui.

Example: Validare con uno schema registrato
```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`

Una cartella di schemi caricata all'avvio dell'applicazione.

Ogni file `.json` viene interpretato e registrato con `F.newjsonschema()`; il nome del file senza estensione è il nome dello schema. La cartella viene caricata prima delle cartelle con il codice, quindi le azioni possono usarne gli schemi con `@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: Usarlo
```js
NEWACTION('Addresses/create', {
	input: '@Address',
	action: function($, model) {
		$.success();
	}
});
```

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

Type: `method`

Valida e converte un valore.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Object` | yes |  | Il valore da validare. |
| `partial` | `Boolean` | no | `false` | Valida solo i campi presenti nel valore. |
| `error` | `ErrorBuilder` | no | `new ErrorBuilder()` | Un builder che riceve gli errori. |
| `path` | `String` | no |  | Un prefisso per i percorsi degli errori. |

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

Restituisce `{ error, response }`. `response` è il valore convertito: per uno schema oggetto, un nuovo oggetto con solo i campi dello schema, oppure `undefined` quando nessun campo ha un valore. `error` è un `ErrorBuilder` con gli errori, oppure `null` quando non ce ne sono.

Con `partial`, i campi che sono `undefined` nel valore vengono saltati, quindi i campi obbligatori mancanti non fanno fallire la validazione. Passa il tuo `ErrorBuilder` come `error` per raccogliere gli errori di più validazioni in un unico builder.

Example: Validare un 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: Aggiornamento parziale
```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`

Valida un valore e lancia un'eccezione al primo errore.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Object` | yes |  | Il valore da validare. |
| `partial` | `Boolean` | no | `false` | Valida solo i campi presenti nel valore. |
| `path` | `String` | no |  | Un prefisso per i percorsi degli errori. |

Returns: `Object` Il valore convertito.

Restituisce il valore convertito. Quando il valore non è valido, lancia un `Error` con il messaggio del primo errore. Usalo dove un'eccezione è più semplice che controllare `result.error`. Solo gli schemi creati da uno schema inline hanno questo metodo.

Example: Eccezione su dati non validi
```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`

Crea la definizione di un tool AI da uno schema inline.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Il nome del tool. |

Returns: `Object` La definizione del tool.

Restituisce un oggetto function-tool per i modelli AI. Ogni campo diventa un parametro con il suo `type` e, come descrizione, il messaggio `//` del campo (una stringa vuota se manca). I campi obbligatori dello schema sono i parametri obbligatori. La descrizione del tool è `schema.summary` o `schema.description` quando ne imposti uno. Esiste sugli schemi creati da uno schema inline (`toJSONSchema()`, `NEWSCHEMA()`), non sugli oggetti JSON Schema registrati con `F.newjsonschema()`. Vedi [Modelli AI](../../guides/ai-models/).

Example: Un tool da uno 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`

Converte uno schema inline in un oggetto JSON Schema con nome per i modelli AI.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Il nome dell'oggetto. |
| `description` | `String` | no |  | Una descrizione dell'oggetto. |

Returns: `Object` L'oggetto JSON Schema.

Restituisce `{ name, description, type: 'object', properties, required, additionalProperties: false }`. Le proprietà usano JSON Schema standard: `Date` è `{ type: 'string', format: 'date-time' }`, `Email` ha `format: 'email'`, un enum ha `enum`, un array ha `items` e un tipo che può essere `null` (come `String2`, `UID`, `GUID`, `JSON`, `IP` o `Base64`) è `['string', 'null']`. Il messaggio `//` di un campo è la sua `description`. `required` viene omesso quando nessun campo è obbligatorio. Come `toAITool()`, esiste sugli schemi creati da uno schema inline.

Example: Una risposta strutturata
```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`

Contrassegna un campo di uno schema inline come obbligatorio.

Un campo obbligatorio fallisce quando il suo valore è vuoto. Per le stringhe è un valore vuoto prima del trim (un testo di soli spazi passa e diventa `''`); per i numeri un valore mancante o non numerico (`0` passa); per i booleani un valore mancante (`false` passa); per le date un valore che non può essere interpretato; per gli array un array vuoto o un valore che non è un array. Un oggetto annidato obbligatorio (`{...}` o `@name`) non fallisce quando manca. `!` equivale a `*`.

Example: Campi obbligatori
```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`

Imposta un messaggio di errore personalizzato per un campo di uno schema inline.

Il testo dopo `//` è il messaggio di errore del campo. Poiché le virgole separano i campi, il messaggio non può contenere virgole; scrivi lo schema su più righe (un campo per riga) quando i messaggi sono lunghi. I messaggi vengono salvati in `schema.errors`.

Example: Messaggi personalizzati
```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`

Valori di testo.

Qualsiasi valore viene convertito in stringa, sottoposto a trim, e gli spazi non separabili diventano spazi normali. Un valore mancante è `''`. `String(50)` imposta la lunghezza massima; un testo più lungo è un errore. La lunghezza viene controllata prima del trim, quindi gli spazi attorno al testo contano. `Text` equivale a `String`. `String2` trasforma un valore vuoto in `null`.

Example: Stringhe
```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`

Valori numerici.

Un numero resta un numero; una stringa con cifre viene interpretata con `String.parseFloat()` (`'33'` dà `33`, `'1,5'` dà `1.5`). Gli altri valori sono trattati come mancanti e il campo viene omesso dalla risposta. `Number2`, `Int`, `Integer`, `Float` e `Decimal` sono nomi dello stesso tipo.

Example: Numeri
```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`

Un numero da -32767 a 32767.

Interpretato come `Number`; un valore fuori intervallo è un errore.

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`

Un numero da 0 a 255.

Interpretato come `Number`; un valore fuori intervallo è un errore.

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

### name:Boolean  name:Bool

Type: `type`

Vero o falso.

Un booleano resta com'è; gli altri valori vengono interpretati con `String.parseBoolean()` (`'true'`, `'1'`, `'on'` danno `true`). Il campo è sempre presente nella risposta: un valore mancante è `false`.

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

### name:Date

Type: `type`

Una data.

Un `Date` resta com'è; gli altri valori vengono interpretati con `String.parseDate()`. Un valore che non può essere interpretato, un valore mancante o una data precedente al 1° gennaio 1970 è `null`.

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

### name:Email

Type: `type`

Un indirizzo email.

Tutti gli spazi vengono rimossi e il valore viene convertito in minuscolo, poi controllato con `String.isEmail()`. Un valore vuoto è ammesso, a meno che il campo non sia obbligatorio.

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

### name:Email2

Type: `type`

Un indirizzo e-mail senza il suo tag.

Funziona come `Email` e in più rimuove il tag dell'indirizzo: la parte da `+` a `@`, così `name+tag@domain.com` diventa `name@domain.com`. Usalo quando una persona non deve registrarsi due volte con indirizzi con tag. Negli schemi JSON è `subtype: 'email2'`; `toAIObject()` e il server MCP lo descrivono come `format: 'email'`.

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

### name:Phone

Type: `type`

Un numero di telefono.

Gli spazi vengono rimossi, poi il valore viene controllato con `String.isPhone()`.

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

### name:URL

Type: `type`

Un indirizzo URL.

Ripulito dagli spazi e controllato con `String.isURL()`.

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

### name:Zip

Type: `type`

Un CAP.

Ripulito dagli spazi e controllato con `String.isZIP()`.

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

### name:UID

Type: `type`

Un identificatore univoco di Total.js.

Ripulito dagli spazi e controllato con `String.isUID()`, il formato generato da `UID()`. Un valore vuoto diventa `null`.

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

### name:GUID

Type: `type`

Un GUID.

Ripulito dagli spazi e controllato con `String.isGUID()`. Un valore vuoto diventa `null`.

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

### name:Name

Type: `type`

Un nome di persona.

Il valore viene formattato con `String.toName()`: ogni parola inizia con una lettera maiuscola.

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

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

Type: `type`

Testo in minuscolo o maiuscolo.

`Lower` e `Lowercase` ripuliscono il valore dagli spazi e lo convertono in minuscolo. `Upper` e `Uppercase` lo convertono in maiuscolo.

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

### name:Capitalize  name:Capitalize2

Type: `type`

Testo con iniziali maiuscole.

`Capitalize` mette in maiuscolo la prima lettera di ogni parola. `Capitalize2` mette in maiuscolo solo la prima lettera del testo.

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`

Un colore esadecimale.

Il valore deve essere `#RGB`, `#RRGGBB` o `#RRGGBBAA` (lettere maiuscole o minuscole).

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

### name:Icon

Type: `type`

Una classe di icona.

Il valore deve essere una classe di icona di Total.js icons o di Font Awesome: un prefisso (`ti`, `tic`, `fa`, `far`, `fab`, `fad`, `fal`, `fas`), uno spazio e il nome dell'icona con un prefisso `ti-`, `tic-` o `fa-`, ad esempio `ti ti-home` o `fas fa-check`.

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

### name:Base64

Type: `type`

Una stringa Base64.

Ripulita dagli spazi e controllata con `String.isBase64()`. Un valore vuoto diventa `null`.

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

### name:JSON

Type: `type`

Un testo JSON.

Ripulito dagli spazi e controllato con `String.isJSON()`: il valore deve iniziare e finire come un oggetto, un array o una stringa JSON, oppure essere un numero. Il contenuto non viene interpretato e il valore resta una stringa; interpretalo con `String.parseJSON()` quando ti serve l'oggetto. Un valore vuoto diventa `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`

Un data URI interpretato in un buffer.

Il valore deve essere un data URI Base64 come `data:image/png;base64,...`. Viene interpretato con `String.parseDataURI()` in `{ type, buffer }`, dove `type` è il content type e `buffer` i dati decodificati. Un valore vuoto diventa `null`.

Example: Caricare una foto come 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`

Un indirizzo IP.

Ripulito dagli spazi e controllato con `net.isIP()` di Node.js: un indirizzo IPv4 canonico (`10.0.0.1`) o un indirizzo IPv6 (`::1`). Un nome host o una forma breve come `127.1` non è valido. Un valore vuoto diventa `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`

Un data URI mantenuto come testo.

Il valore deve essere un data URI Base64, come `DataURI`, ma non viene interpretato: la risposta contiene il testo originale. Usalo quando salvi il data URI così com'è. Un valore vuoto diventa `null`.

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

### name:SafeString

Type: `type`

Testo senza pattern di XSS o SQL injection.

Ripulito dagli spazi e rifiutato quando `String.isXSS()` o `String.isSQLInjection()` trova un pattern pericoloso, come un tag HTML.

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`

Una frase di ricerca normalizzata.

Ripulita dagli spazi e convertita con `String.toSearch()`: minuscolo, senza segni diacritici e con lettere semplificate, così può essere confrontata con il testo di ricerca indicizzato.

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

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

Type: `type`

Un valore da un elenco fisso.

In uno schema inline, elenca i valori tra parentesi graffe, separati da `|` o `;`. In uno schema JSON, usa la parola chiave `enum` con un array. Un valore che non è nell'elenco è un errore; un valore vuoto è ammesso, a meno che il campo non sia obbligatorio.

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

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

### name:[Type]

Type: `type`

Un array di valori di un tipo.

Il valore deve essere un array; qualsiasi altra cosa fa omettere il campo (o fallire, quando il campo è obbligatorio). Ogni elemento viene convertito nel tipo, ad esempio `[Number]` trasforma `['1', 2]` in `[1, 2]`. `[{...}]` è un array di oggetti annidati e `[@name]` un array validato da uno schema registrato; i percorsi degli errori contengono l'indice, come `items[1].price`.

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

Un oggetto annidato.

Le parentesi graffe con dei campi (non un enum) creano un oggetto annidato con i propri campi, modificatori e tipi. L'oggetto annidato viene validato come quello principale e i suoi errori hanno percorsi come `address.city`. Un oggetto annidato può contenere ulteriori oggetti annidati e array, per esempio `order:{lines:[{sku:String,qty:Number}],shipping:{address:{city:String}}}`.

Example: Oggetto annidato
```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`

Un oggetto annidato validato da uno schema registrato.

Il valore viene validato dallo schema registrato come `Schema` (con `NEWSCHEMA()`, `F.newjsonschema()` o la cartella `jsonschemas/`). `[@Schema]` valida ogni elemento di un array. Gli errori mantengono i percorsi dell'oggetto annidato.

Example: Riutilizzare uno 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`

I campi obbligatori di uno schema di oggetto.

Un array di nomi di proprietà. Le regole per i valori vuoti sono le stesse di `*` negli schemi inline.

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`

Una parola chiave di Total.js che seleziona una conversione speciale.

Per le proprietà `string`, `subtype` usa la conversione di un tipo inline: `email`, `email2`, `phone`, `url`, `zip`, `uid`, `guid`, `name`, `lower`, `lowercase`, `upper`, `uppercase`, `capitalize`, `capitalize2`, `color`, `icon`, `base64`, `datauri`, `datauri2`, `safestring`, `search`, `json` o `ip`. `ipaddress` è uguale a `ip` ed esiste solo negli schemi JSON. Per le proprietà `number`, `smallint` e `tinyint` controllano l'intervallo. Una stringa vuota resta `''`; aggiungi `nullable: true` per ottenere `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`

Una parola chiave di Total.js che trasforma una stringa vuota in null.

Per una proprietà `string`, un valore vuoto diventa `null` invece di `''`. I tipi inline `String2`, `UID`, `GUID`, `Base64`, `DataURI` e `DataURI2` lo impostano automaticamente.

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`

I limiti di lunghezza di una stringa.

`minLength` e `maxLength` controllano il numero di caratteri di una stringa. `String(50)` in uno schema inline imposta `maxLength`.

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

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

Type: `property`

I limiti di un numero.

`minimum` e `maximum` sono limiti inclusivi, `exclusiveMinimum` ed `exclusiveMaximum` esclusivi. `multipleOf` richiede un valore divisibile per il numero indicato.

Example: Limiti numerici
```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`

Lo schema degli elementi di un array.

`items` è un unico schema per ogni elemento: un tipo con le sue parole chiave (`string`, `number`, `boolean`, `date`), un `object` con le sue `properties` e il suo `required`, o un `$ref`. Ogni elemento che è un oggetto viene validato e convertito come un oggetto annidato; un errore di un elemento ha il nome e il percorso `field.property` e la posizione dell'elemento in `index`. `minItems` imposta il numero minimo di elementi di un array non vuoto; un array vuoto fallisce solo quando il campo è obbligatorio. `uniqueItems: true` rimuove i valori duplicati.

Example: Array di tag
```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 di oggetti
```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`

Un riferimento a un altro schema.

`$ref` valida un oggetto (o ogni elemento di un array, in `items`) con un altro schema. Un valore che inizia con `#/` punta alle `definitions` dello stesso schema, ad esempio `#/definitions/Address`. Qualsiasi altro valore è il nome o l'`$id` di uno schema registrato in `F.jsonschemas`.

Example: Riferimenti locali e registrati
```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`

Un elenco di errori con uno stato HTTP.

Returns: `ErrorBuilder`

La validazione restituisce i suoi errori in un `ErrorBuilder`, e azioni e controller rispondono con esso come array JSON. Puoi crearne uno per raccogliere i tuoi errori. Le sue proprietà: `items` (gli errori grezzi), `length` (il numero di errori), `status` (lo stato HTTP, `400` di default) e `prefix` (un testo messo prima dei nomi degli errori di campo).

Example: Raccogliere errori
```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`

Aggiunge un messaggio di errore o uno stato HTTP.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `error` | `String|Number` | yes |  | Un messaggio o un codice di stato HTTP. |
| `path` | `String` | no |  | Il percorso del campo. |
| `index` | `Number` | no |  | L'indice di un elemento di un array. |

Returns: `ErrorBuilder` Lo stesso builder.

Un numero da 400 in su imposta `status` e aggiunge il testo dello stato HTTP, ad esempio `404` aggiunge `404: Not Found`. Qualsiasi altro valore viene aggiunto come messaggio. Senza valore, viene inserito `401`. Un messaggio che inizia con `@(` viene tradotto da `output()`, ad esempio `err.push('@(Access denied)')`.

Example: Messaggi e stati
```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`

Aggiunge un errore di un campo, con un messaggio facoltativo.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Il nome del campo. |
| `path` | `String` | no |  | Il percorso del campo. |
| `index` | `Number` | no |  | L'indice di un elemento di un array. |

Returns: `ErrorBuilder` Lo stesso builder.

Aggiunge un errore per il campo `name` (preceduto da `prefix`). Senza `error`, il messaggio viene risolto da `output()`: prima i messaggi `//` dello schema, poi la risorsa con il nome del campo nella lingua dell'output, poi `The field "name" is invalid`. Con `error`, quel testo è il messaggio.

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

Example: Errore di campo
```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`

Restituisce gli errori come array di oggetti.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `language` | `String` | no | `'default'` | La lingua per risorse e traduzioni. |

Returns: `Array` L'elenco degli errori.

Ogni elemento è `{ name, error, path, index }` con il messaggio finale. I messaggi degli errori dei campi vengono letti dalle risorse di `language`, i testi `@(...)` vengono tradotti e vengono applicate le sostituzioni di `replace()`. Quando esiste un handler globale `ErrorBuilder.transform()`, viene restituito invece il suo risultato.

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

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

Type: `method`

Restituisce i messaggi come un unico testo.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `language` | `String` | no | `'default'` | La lingua. |
| `divider` | `String` | no | `'\n'` | Il testo tra i messaggi. |

Returns: `String`

I messaggi di `output(language)` uniti da `divider`.

Example: Testo
```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`

Restituisce gli errori come oggetto Error.

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

Returns: `Error`

Crea `new Error()` con tutti i messaggi uniti senza separatore. Utile per rifiutare una promise.

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

### err.throw()

Type: `method`

Fa lanciare al builder un'eccezione al prossimo errore.

Returns: `ErrorBuilder` Lo stesso builder.

Dopo `throw()`, ogni `push()` o `push2()` lancia un `Error` con il messaggio del primo errore. `schema.validate()` lo usa.

Example: Eccezione immediata
```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`

Sostituisce un testo in tutti i messaggi.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `search` | `String` | yes |  | Il testo da cercare. |
| `value` | `String` | yes |  | Il nuovo testo. |

Returns: `ErrorBuilder` Lo stesso builder.

La sostituzione viene applicata da `output()` a ogni messaggio, così puoi inserire un messaggio con un segnaposto e completarlo in seguito.

Example: Segnaposto
```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`

Crea un builder da un output di errori, un messaggio o un Error.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `Array|String|Number|Error` | yes |  | Gli errori. |

Returns: `ErrorBuilder` Un nuovo builder.

Con un array, viene aggiunto ogni elemento che ha `error` (ad esempio gli errori JSON restituiti da un'altra app Total.js). Un numero o una stringa viene inserito, e un `Error` viene inserito come suo testo.

Example: Errori da un altro servizio
```js
var err = ErrorBuilder.assign([{ name: 'email', error: 'Email is taken' }]);
err.length; // 1
```

### ErrorBuilder.transform(callback)

Type: `method`

Imposta un handler globale che modifica l'output di ogni ErrorBuilder.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function` | yes |  | `function(output, language)` che restituisce il nuovo output. |

`callback(output, language)` riceve l'array creato da `output()` e restituisce ciò che `output()` restituirà al suo posto. Poiché azioni e controller inviano `output()` al client, questo cambia il formato di tutte le risposte di errore.

Example: Un formato di errore personalizzato
```js
ErrorBuilder.transform(function(output, language) {
	return { success: false, errors: output };
});
```
