To enable type coercion pass option coerceTypes to ajv (it is false by default). See example.
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 (e.g., in
anyOf).
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.
Possible type coercions:
| from type → to type ↓ |
string | number | boolean | null |
|---|---|---|---|---|
| string | - | x→""+x |
false→"false"true→"true" |
null→"" |
| number / integer |
Valid number / integer: x→+x |
- | false→0true→1 |
null→0 |
| boolean | "false"→false"true"→true"abc"↛""↛ |
0→false1→truex↛ |
- | null→false |
| null | ""→null"null"↛"abc"↛ |
0→nullx↛ |
false→nulltrue↛ |
- |
Coercion to number is possible if the string is a valid number, +data is used.
Coercion to integer is possible if the string is a valid number without fractional part (data % 1 === 0).
Unlike JavaScript, only these strings can be coerced to boolean:
"true"->true"false"->false
Empty string is coerced to null, other strings can't be coerced.
Always possible, '' + data is used
Unlike JavaScript, only these numbers can be coerced to boolean:
1->true0->false
0 coerces to null, other numbers can't be coerced.
true->"true"false->"false"
true->1false->0
false coerces to null, true can't be coerced.
null coerses to the empty string.
null coerces to 0
null coerces to false