From 9e18e68ce7788fcab00375526e78a42aa8bd26a8 Mon Sep 17 00:00:00 2001 From: will Farrell Date: Fri, 22 Jul 2016 18:07:10 -0600 Subject: [PATCH] Add in ability to coerce to an array --- COERCION.md | 10 +++- lib/ajv.d.ts | 2 +- lib/compile/util.js | 5 +- lib/dot/coerce.def | 4 ++ lib/dot/validate.jst | 2 +- spec/coercion.spec.js | 132 +++++++++++++++++++++++++++--------------- 6 files changed, 105 insertions(+), 50 deletions(-) diff --git a/COERCION.md b/COERCION.md index b17d59a..bcec029 100644 --- a/COERCION.md +++ b/COERCION.md @@ -1,6 +1,6 @@ # Ajv type coercion rules -To enable type coercion pass option `coerceTypes` to Ajv (it is `false` by default). See [example](https://github.com/epoberezkin/ajv#coercing-data-types). +To enable type coercion pass option `coerceTypes` to Ajv with `true` or `array` (it is `false` by default). See [example](https://github.com/epoberezkin/ajv#coercing-data-types). The coercion rules are different from JavaScript: - to validate user input as expected @@ -11,6 +11,8 @@ Type coercion only happens if there is `type` keyword and if without coercion th 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. +If `coerceTypes` is set to `array` + Possible type coercions: |from type →
to type ↓|string|number|boolean|null| @@ -98,3 +100,9 @@ Unlike JavaScript, only these numbers can be coerced to `boolean`: #### To boolean type `null` coerces to `false` + +## Coersion from array + +Wraps and non-array input in an array. + +- `"foo"` -> `[ "foo" ]` \ No newline at end of file diff --git a/lib/ajv.d.ts b/lib/ajv.d.ts index be48ef7..8c05faf 100644 --- a/lib/ajv.d.ts +++ b/lib/ajv.d.ts @@ -110,7 +110,7 @@ declare namespace ajv { loadSchema?: (uri: string, cb: (err: Error, schema: Object) => any) => any; removeAdditional?: boolean | string; useDefaults?: boolean | string; - coerceTypes?: boolean; + coerceTypes?: boolean | string; async?: boolean | string; transpile?: string | ((code: string) => string); meta?: boolean | Object; diff --git a/lib/compile/util.js b/lib/compile/util.js index 626884b..7e7f45b 100644 --- a/lib/compile/util.js +++ b/lib/compile/util.js @@ -75,16 +75,19 @@ function checkDataTypes(dataTypes, data) { var COERCE_TO_TYPES = toHash([ 'string', 'number', 'integer', 'boolean', 'null' ]); -function coerceToTypes(dataTypes) { +function coerceToTypes(optionCoerceTypes, dataTypes) { if (Array.isArray(dataTypes)) { var types = []; for (var i=0; i