coerceTypes option readme, closes #95

master
Evgeny Poberezkin 2016-01-17 15:05:01 +00:00
parent 0c60364a7f
commit d1ca4874c0
3 changed files with 128 additions and 1 deletions

89
COERCION.md Normal file
View File

@ -0,0 +1,89 @@
# Ajv type coercion rules
The coercion rules are different from JavaScript:
- to validate user input as expected
- to have the coercion reversible
- to correctly validate cases where different types are required in subschemas.
Type coercion only happens if there is `type` keyword and if without coercion the validation would have failed. If coercion to the required type succeeds then the validation continues to other keywords, otherwise the validation fails.
If there are multiple types allowed in `type` keyword the coercion will only happen if none of the types match the data and some of the scalar types are present (coercion to/from `object`/`array` is not possible). In this case the validating function will try coercing the data to each type in order until some of them succeeds.
## Coersion from string values
#### To number type
Coercion to `number` is possible if the string is a valid number, `+data` is used.
#### To integer type
Coercion to `integer` is possible if the string is a valid number without fractional part (`data % 1 === 0`).
#### To boolean type
Unlike JavaScript, only these strings can be coerced to `boolean`:
- `"true"` -> `true`
- `"false"` -> `false`
#### To null type
Empty string is coerced to `null`, other strings can't be coerced.
## Coercion from number values
#### To string type
Always possible, `'' + data` is used
#### To boolean type
Unlike JavaScript, only these numbers can be coerced to `boolean`:
- 1 -> `true`
- 0 -> `false`
#### To null type
`0` coerces to `null`, other numbers can't be coerced.
## Coercion from boolean values
#### To string type
- `true` -> `"true"`
- `false` -> `"false"`
#### To number/integer types
- `true` -> 1
- `false` -> 0
#### To null type
`false` coerces to `null`, `true` can't be coerced.
## Coercion from null
#### To string type
`null` coerses to the empty string.
#### To number/integer types
`null` coerces to `0`
#### To boolean type
`null` coerces to `false`

View File

@ -29,6 +29,7 @@ NB: [Changes in version 3.0.0](https://github.com/epoberezkin/ajv/releases/tag/3
- i18n error messages support with [ajv-i18n](https://github.com/epoberezkin/ajv-i18n) package (version >= 1.0.0)
- [filtering data](#filtering-data) from additional properties
- NEW: [assigning defaults](#assigning-defaults) to missing properties and items
- NEW: [coerce data](#coerce-data-types) to the types specified in `type` keywords
- [custom keywords](#defining-custom-keywords)
- keywords `switch`, `constant`, `contains`, `patternGroups`, `formatMaximum` / `formatMinimum` and `exclusiveFormatMaximum` / `exclusiveFormatMinimum` from [JSON-schema v5 proposals](https://github.com/json-schema/json-schema/wiki/v5-Proposals) with [option v5](#options)
- [v5 meta-schema](https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/json-schema-v5.json#) for schemas using v5 keywords
@ -519,6 +520,41 @@ console.log(data); // [ 1, "foo" ]
- in schemas generated by custom macro keywords
## Coerce data types
When you are validating user inputs all your data properties are usually strings. The option `coerceTypes` allows you to have your data types coerced to the types specified in your schema `type` keywords, both to pass the validation and to use the correctly typed data afterwards.
This option modifies original data.
Please note, that if you pass a scalar value to the validating function its type will be coerced and it will pass the validation, but the value of the variable you pass won't be updated because scalars are passed by value.
Example:
```
var ajv = Ajv({ coerceTypes: true });
var schema = {
"type": "object",
"properties": {
"foo": { "type": "number" },
"bar": { "type": "boolean" }
},
"required": [ "foo", "bar" ]
};
var data = { "foo": "1", "bar": "false" };
var validate = ajv.compile(schema);
console.log(validate(data)); // true
console.log(data); // { "foo": 1, "bar": false }
```
The coercion rules, as you can see from the example, are different from JavaScript both to validate user input as expected and to have the coercion reversible (to correctly validate cases where different types are defined in subschemas of "anyOf" and other compound keywords).
See [Coercion rules](https://github.com/epoberezkin/ajv/blob/master/COERCION.md) for details.
## API
##### Ajv(Object options) -> Object
@ -663,6 +699,7 @@ Defaults:
allErrors: false,
removeAdditional: false,
useDefaults: false,
coerceTypes: false,
verbose: false,
format: 'fast',
formats: {},
@ -693,6 +730,7 @@ Defaults:
- `true` - only additional properties with `additionalProperties` keyword equal to `false` are removed.
- `"failing"` - additional properties that fail schema validation will be removed (where `additionalProperties` keyword is `false` or schema).
- _useDefaults_: replace missing properties and items with the values from corresponding `defaults` keywords. Default behaviour is to ignore `default` keywords. This option is not used if schema is added with `addMetaSchema` method. See example in [Assigning defaults](#assigning-defaults).
- _coerceTypes_: change data type of data to match `type` keyword. See the example in [Coerce data types](#coerce-data-types) and [coercion rules](https://github.com/epoberezkin/ajv/blob/master/COERCION.md).
- _verbose_: include the reference to the part of the schema (`schema` and `parentSchema`) and validated data in errors (false by default).
- _format_: formats validation mode ('fast' by default). Pass 'full' for more correct and slow validation or `false` not to validate formats at all. E.g., 25:00:00 and 2015/14/33 will be invalid time and date in 'full' mode but it will be valid in 'fast' mode.
- _formats_: an object with custom formats. Keys and values will be passed to `addFormat` method.

View File

@ -1,6 +1,6 @@
{
"name": "ajv",
"version": "3.3.1",
"version": "3.4.0",
"description": "Another JSON Schema Validator",
"main": "lib/ajv.js",
"files": [