Comparing version 0.10.1 to 0.11.0
@@ -0,2 +1,9 @@ | ||
v0.11.0 - Sun, 08 Nov 2015 17:17:09 GMT | ||
--------------------------------------- | ||
- [686f6b1](../../commit/686f6b1) [changed] concat() allows mixing "mixed" and other type | ||
## 0.9.0 | ||
@@ -3,0 +10,0 @@ __breaking__ |
@@ -48,3 +48,3 @@ 'use strict'; | ||
if (schema._type !== this._type) throw new TypeError('You cannot `concat()` schema\'s of different types: ' + this._type + ' and ' + schema._type); | ||
if (schema._type !== this._type && this._type !== 'mixed') throw new TypeError('You cannot `concat()` schema\'s of different types: ' + this._type + ' and ' + schema._type); | ||
@@ -61,2 +61,4 @@ var next = _.merge(this.clone(), schema.clone()); | ||
next._type = schema._type; | ||
return next; | ||
@@ -220,3 +222,2 @@ }, | ||
next = this.clone(), | ||
errorMsg, | ||
isExclusive; | ||
@@ -223,0 +224,0 @@ |
@@ -31,3 +31,4 @@ 'use strict'; | ||
if (options.then && options.then._type !== type || options.otherwise && options.otherwise._type !== type) throw new TypeError('cannot create polymorphic conditionals, `then` and `otherwise` must be the same type: ' + type); | ||
// if( options.then && options.then._type !== type || options.otherwise && options.otherwise._type !== type) | ||
// throw new TypeError(`cannot create polymorphic conditionals, \`then\` and \`otherwise\` must be the same type: ${type}`) | ||
@@ -34,0 +35,0 @@ is = typeof is === 'function' ? is : (function (is, value) { |
{ | ||
"name": "yup", | ||
"version": "0.10.1", | ||
"version": "0.11.0", | ||
"description": "Dead simple Object schema validation", | ||
@@ -24,2 +24,3 @@ "main": "lib/index.js", | ||
"babel": "^5.8.23", | ||
"babel-eslint": "^4.1.4", | ||
"babel-loader": "^5.3.2", | ||
@@ -29,2 +30,3 @@ "babel-plugin-external-helpers": "^1.1.1", | ||
"chai-as-promised": "^4.1.1", | ||
"eslint": "^0.24.1", | ||
"karma": "^0.13.14", | ||
@@ -39,2 +41,3 @@ "karma-chrome-launcher": "^0.2.0", | ||
"mocha": "^1.21.4", | ||
"mt-changelog": "^0.6.2", | ||
"node-libs-browser": "^0.5.2", | ||
@@ -41,0 +44,0 @@ "phantomjs": "^1.9.17", |
284
README.md
Yup | ||
======================= | ||
Yup is a js object schema validator and object parser. The api and style is heavily inspired by [Joi](https://github.com/hapijs/joi), which is an amazing library but is generally too large and difficult to package for use in a browser. Yup is a leaner in the same spirit without some of the fancy features. You can use it on the server as well, but in that case you might as well just use Joi. | ||
Yup is a JavaScript object schema validator and object parser. The API and style is ~~stolen~~ heavily inspired | ||
by [Joi](https://github.com/hapijs/joi), which is an amazing library but is generally too large and difficult | ||
to package for use in a browser. Yup is a leaner in the same spirit without some of the fancy features. | ||
You can use it on the server as well, but in that case you might as well just use Joi. | ||
Yup is also a a good bit less opinionated than joi, allowing for custom transformations and async validation. It also allows "stacking" conditions via `when` for properties that depend on more than one other sibling or child property. Yup seperates the parsing and validating functions into seperate steps so it can be used to parse json seperate from validating it, via the `cast` method. | ||
Yup is also a a good bit less opinionated than joi, allowing for custom transformations and async validation. | ||
It also allows "stacking" conditions via `when` for properties that depend on more than one other sibling or | ||
child property. Yup separates the parsing and validating functions into separate steps so it can be used to parse | ||
json separate from validating it, via the `cast` method. | ||
@@ -20,37 +26,38 @@ ## Usage | ||
- [`addMethod`](#addmethodschematype-name-method) | ||
- [`ValidationError`](#validationerrorstringarraystring-errors-string-path-any-value) | ||
- [`ValidationError`](#validationerrorstringarraystring-errors-string-path-any-value) | ||
- [Extending Schema Types](#extending-schema-types) | ||
You define and create schema objects. Schema objects are immutable, so each call of a method returns a _new_ schema object. | ||
var yup = require('yup') | ||
var schema = yup.object().shape({ | ||
name: yup.string().required(), | ||
age: yup.number().required().positive().integer(), | ||
email: yup.string().email(), | ||
website yup.string().url(), | ||
createdOn: yup.date().default(function() { | ||
return new Date | ||
}), | ||
}) | ||
```js | ||
var yup = require('yup') | ||
//check validity | ||
schema.isValid({ | ||
name: 'jimmy', | ||
age: 24 | ||
}) | ||
.then(function(valid){ | ||
valid // => true | ||
}) | ||
var schema = yup.object().shape({ | ||
name: yup.string().required(), | ||
age: yup.number().required().positive().integer(), | ||
email: yup.string().email(), | ||
website yup.string().url(), | ||
createdOn: yup.date().default(function() { | ||
return new Date | ||
}), | ||
}) | ||
//check validity | ||
schema.isValid({ | ||
name: 'jimmy', | ||
age: 24 | ||
}) | ||
.then(function(valid){ | ||
valid // => true | ||
}) | ||
//you can try and type cast objects to the defined schema | ||
schema.cast({ | ||
name: 'jimmy', | ||
age: '24', | ||
createdOn: '2014-09-23T19:25:25Z' | ||
}) | ||
// => { name: 'jimmy', age: 24, createdOn: Date } | ||
//you can try and type cast objects to the defined schema | ||
schema.cast({ | ||
name: 'jimmy', | ||
age: '24', | ||
createdOn: '2014-09-23T19:25:25Z' | ||
}) | ||
// => { name: 'jimmy', age: 24, createdOn: Date } | ||
``` | ||
@@ -84,5 +91,5 @@ ### `yup` | ||
nested: object() | ||
.shape({ | ||
.shape({ | ||
arr: array().of( | ||
object().shape({ num: number().max(4) })) | ||
object().shape({ num: number().max(4) })) | ||
}) | ||
@@ -94,3 +101,3 @@ }) | ||
reach(schema, 'nested.arr[1].num') | ||
reach(schema, 'nested["arr"][1].num') | ||
reach(schema, 'nested["arr"][1].num') | ||
``` | ||
@@ -104,7 +111,7 @@ | ||
yup.addMethod(yup.date, 'format', function(formats, parseStrict) { | ||
return this.transform(function(value, originalValue){ | ||
if ( this.isType(value) ) return value | ||
if ( this.isType(value) ) return value | ||
value = Moment(originalValue, formats, parseStrict) | ||
@@ -123,3 +130,5 @@ | ||
- `errors`: array of error messages | ||
- `inner`: in the case of aggregate errors, inner is an array of `ValidationErrors` throw earlier in the validation chain. When the `abortEarly` option is `false` this is where you can inspect each error thrown, alternatively `errors` will have all the of the messages from each inner error. | ||
- `inner`: in the case of aggregate errors, inner is an array of `ValidationErrors` throw earlier in the | ||
validation chain. When the `abortEarly` option is `false` this is where you can inspect each error thrown, | ||
alternatively `errors` will have all the of the messages from each inner error. | ||
@@ -135,3 +144,3 @@ | ||
valid //=> true | ||
}) | ||
}) | ||
``` | ||
@@ -141,3 +150,3 @@ | ||
Creates a deep copy of the schema. Clone is used internally to return a new schema with every schema state change. | ||
Creates a deep copy of the schema. Clone is used internally to return a new schema with every schema state change. | ||
@@ -150,12 +159,18 @@ #### `mixed.concat(Schema schema)` | ||
Returns the value (a cast value if `isStrict` is `false`) if the value is valid, and returns the errors otherwise. This method is __asynchronous__ and returns a Promise object, that is fulfilled with the value, or rejected with a `ValidationError`. If you are more comfortable with Node style callbacks, then you can provide one to be called when the validation is complete (called with the Error as the first argument, and value | ||
Returns the value (a cast value if `isStrict` is `false`) if the value is valid, and returns the errors otherwise. | ||
This method is __asynchronous__ and returns a Promise object, that is fulfilled with the value, or rejected | ||
with a `ValidationError`. If you are more comfortable with Node style callbacks, then you can provide one | ||
to be called when the validation is complete (called with the Error as the first argument, and value | ||
as the second). | ||
The `options` argument is an object hash containing any schema options you may want to override (or specify for the first time). | ||
The `options` argument is an object hash containing any schema options you may want to override | ||
(or specify for the first time). | ||
- `strict` -> boolean: default `false`, only validate the input, and skip and coercion or transformation | ||
- `abortEarly` -> boolean: default `true`, return from validation methods on the first error rather than after all validations run. | ||
- `abortEarly` -> boolean: default `true`, return from validation methods on the first error rather | ||
than after all validations run. | ||
- `stripUnknown` -> boolean: default `false` remove unspecified keys from objects. | ||
- `recursive` -> boolean: default `true` when `false` validations will not descend into sub schemas (relavant for objects or arrays). | ||
- `recursive` -> boolean: default `true` when `false` validations will not descend into sub schemas | ||
(relavant for objects or arrays). | ||
- `context` -> an `object` containing any context for validating schema conditions (see: `when()`) | ||
@@ -191,3 +206,6 @@ | ||
Returns `true` when the passed in value matches the schema. if `false` then the schema also has a `.errors` field which is an array of validation error messages (strings), thrown by the schema. `isValid` is __asynchronous__ and returns a Promise object. If you are more comfortable with Node style callbacks, providing a function as teh last argument will opt into that interface. | ||
Returns `true` when the passed in value matches the schema. if `false` then the schema also has a `.errors` | ||
field which is an array of validation error messages (strings), thrown by the schema. `isValid` | ||
is __asynchronous__ and returns a Promise object. If you are more comfortable with Node style callbacks, | ||
providing a function as the last argument will opt into that interface. | ||
@@ -198,15 +216,23 @@ Takes the same options as `validate()`. | ||
Attempts to coerce the passed in value to a value that matches the schema. For example: `'5'` will cast to `5` when using the `number()` type. Failed casts generally return `null`, but may also return results like `NaN` and unexpected strings. | ||
Attempts to coerce the passed in value to a value that matches the schema. For example: `'5'` will | ||
cast to `5` when using the `number()` type. Failed casts generally return `null`, but may also | ||
return results like `NaN` and unexpected strings. | ||
#### `mixed.isType(Any value) -> Boolean` | ||
Runs a type check against the passed in `value`. It returns true if it matches, it does not cast the value. When `nullable()` is set `null` is considered a valid value of the type. You should use `isType` for all Schema type checks. | ||
Runs a type check against the passed in `value`. It returns true if it matches, | ||
it does not cast the value. When `nullable()` is set `null` is considered a valid value of the type. | ||
You should use `isType` for all Schema type checks. | ||
#### `mixed.strict()` (default: `false`) | ||
Sets the `strict` option to `true`. Strict schemas skip coercion and transformation attempts, validating the value "as is". | ||
Sets the `strict` option to `true`. Strict schemas skip coercion and transformation attempts, | ||
validating the value "as is". | ||
#### `mixed.default(Any value)` | ||
Sets a default value to use when the value is `undefined` (or `null` when the schema is not nullable). Defaults are created after transformations are executed, but before validations, to help ensure that safe defaults are specified. The default value will be cloned on each use wich can incur performance penalty for objects and arrays. To avoid this overhead you can also pass a function that returns an new default. | ||
Sets a default value to use when the value is `undefined` (or `null` when the schema is not nullable). | ||
Defaults are created after transformations are executed, but before validations, to help ensure that safe | ||
defaults are specified. The default value will be cloned on each use, which can incur performance penalty | ||
for objects and arrays. To avoid this overhead you can also pass a function that returns an new default. | ||
@@ -231,7 +257,8 @@ ```js | ||
Define an error message for failed type checks. The `${value}` and `${type}` interpolation can be used in the `message` argument. | ||
Define an error message for failed type checks. The `${value}` and `${type}` interpolation can | ||
be used in the `message` argument. | ||
#### `mixed.nullable(Bool isNullable)` (default: `false`) | ||
Indicates that `null` is a valid value for the schema. Without `nullable()` | ||
Indicates that `null` is a valid value for the schema. Without `nullable()` | ||
`null` is treated as a different type and will fail `isType()` checks. | ||
@@ -245,3 +272,4 @@ | ||
Whitelist a set of values. Values added are automatically removed from any blacklist if they are in it. The `${values}` interpolation can be used in the `message` argument. | ||
Whitelist a set of values. Values added are automatically removed from any blacklist if they are in it. | ||
The `${values}` interpolation can be used in the `message` argument. | ||
@@ -257,3 +285,4 @@ ```javascript | ||
Blacklist a set of values. Values added are automatically removed from any whitelist if they are in it. The `${values}` interpolation can be used in the `message` argument. | ||
Blacklist a set of values. Values added are automatically removed from any whitelist if they are in it. | ||
The `${values}` interpolation can be used in the `message` argument. | ||
@@ -268,21 +297,26 @@ ```javascript | ||
Adjust the schema based on a sibling or sibling children fields. You can provide an object literal where the key `is` is value or a matcher function, `then` provides the true schema and/or `otherwise` for the failure condition. | ||
Adjust the schema based on a sibling or sibling children fields. You can provide an object | ||
literal where the key `is` is value or a matcher function, `then` provides the true schema and/or | ||
`otherwise` for the failure condition. | ||
`is` conditions are strictly compared (`===`) if you want to use a different form of equality you can provide a function like: `is: (value) => value == true`. | ||
`is` conditions are strictly compared (`===`) if you want to use a different form of equality you | ||
can provide a function like: `is: (value) => value == true`. | ||
Alternatively you can provide a function the returns a schema (called with teh value of the key and teh current schema). `when` conditions are additive. | ||
Alternatively you can provide a function the returns a schema (called with the value of the key | ||
and the current schema). `when` conditions are additive. | ||
Like Joi you can also prefix properties with `$` to specify a property that is dependent on `context` passed in by `validate()` or `isValid`. | ||
Like joi you can also prefix properties with `$` to specify a property that is dependent | ||
on `context` passed in by `validate()` or `isValid`. | ||
```javascript | ||
var inst = yup.object({ | ||
isBig: yup.boolean(), | ||
isBig: yup.boolean(), | ||
count: yup.number() | ||
.when('isBig', { | ||
.when('isBig', { | ||
is: true, // alternatively: (val) => val == true | ||
then: yup.number().min(5), | ||
otherwise: yup.number().min(0) | ||
then: yup.number().min(5), | ||
otherwise: yup.number().min(0) | ||
}) | ||
.when('$other', (other, schema) => other === 4 | ||
? schema.max(6) | ||
.when('$other', (other, schema) => other === 4 | ||
? schema.max(6) | ||
: schema) | ||
@@ -295,11 +329,21 @@ }) | ||
#### `mixed.test(String name, String message, Function fn, [Bool callbackStyleAsync])` | ||
#### `mixed.test(String name, String message, Function fn, [Bool callbackStyleAsync])` | ||
Adds a test function to the validation chain. Tests are run after any object is cast. Many types have some tests built in, but you can create custom ones easily. In order to allow asynchronous custom validations _all_ tests are run asynchronously. A consequence of this is that test execution order cannot be guaranteed. | ||
Adds a test function to the validation chain. Tests are run after any object is cast. | ||
Many types have some tests built in, but you can create custom ones easily. | ||
In order to allow asynchronous custom validations _all_ tests are run asynchronously. | ||
A consequence of this is that test execution order cannot be guaranteed. | ||
All tests must provide a `name`, an error `message` and a validation function that must return `true` or `false` or a `ValidationError`. To make a test async return a promise that resolves `true` or `false` or a `ValidationError`. If you perfer the Node callback style, you can pass `true` for `callbackStyleAsync` and the validation function will pass in an additional `done` function as the last parameter to be called with the validity. | ||
All tests must provide a `name`, an error `message` and a validation function that must return | ||
`true` or `false` or a `ValidationError`. To make a test async return a promise that resolves `true` | ||
or `false` or a `ValidationError`. If you prefer the Node callback style, you can pass `true` for `callbackStyleAsync` | ||
and the validation function will pass in an additional `done` function as the last parameter to | ||
be called with the validity. | ||
for the `message` argument you can provide a string which is will interpolate certain values if specified using the `${param}` syntax. By default all test messages are passed a `path` value which is valuable in nested schemas. | ||
for the `message` argument you can provide a string which is will interpolate certain values | ||
if specified using the `${param}` syntax. By default all test messages are passed a `path` value | ||
which is valuable in nested schemas. | ||
the `test` function is called with the current `value`, along with `path` and `context` if they exist. For more advanced validations you can use the alternate signature to provide more options (see below): | ||
the `test` function is called with the current `value`, along with `path` and `context` if they exist. | ||
For more advanced validations you can use the alternate signature to provide more options (see below): | ||
@@ -323,3 +367,3 @@ ```js | ||
// error argument is for exceptions, not an failed tests | ||
done(null, value === 'jimmy') | ||
done(null, value === 'jimmy') | ||
} | ||
@@ -340,3 +384,5 @@ | ||
- `this.parent`: in the case of nested schema, this is the value of the parent object | ||
- `this.createError(Object: { path: String, message: String })`: create and return a validation error. Useful for dynamically setting the `path`, or more likely, the error `message`. If either option is omitted it will use the current path, or default message. | ||
- `this.createError(Object: { path: String, message: String })`: create and return a | ||
validation error. Useful for dynamically setting the `path`, or more likely, the error `message`. | ||
If either option is omitted it will use the current path, or default message. | ||
@@ -349,11 +395,15 @@ | ||
- `name`: string, all validations must have a name. | ||
- `test`: function(value), the validator run against the value, should return `true` or `false` or a promise that resolves to `true` or `false` | ||
- `test`: function(value), the validator run against the value, should return `true` | ||
or `false` or a promise that resolves to `true` or `false` | ||
- `message`: string, validation error message | ||
- `params`: object, passed to message for interpolation | ||
- `exclusive`: boolean (default `false`), when true, there can only be one active `test` of the same name on a schema, validations of the same name will replace previous ones. when `false` the validations will stack. e.g. `max` is an exclusive validation, whereas the string `matches` is not. This is helpful for "toggling" validations on and off. | ||
- `exclusive`: boolean (default `false`), when true, there can only be one active | ||
`test` of the same name on a schema, validations of the same name will replace previous ones. | ||
when `false` the validations will stack. e.g. `max` is an exclusive validation, | ||
whereas the string `matches` is not. This is helpful for "toggling" validations on and off. | ||
- `useCallback`: boolean (default `false`), use the callback interface for asynchrony instead of promises | ||
```javascript | ||
var schema = yup.mixed().test({ | ||
name: 'max', | ||
var schema = yup.mixed().test({ | ||
name: 'max', | ||
exclusive: true, | ||
@@ -368,5 +418,9 @@ params: { max }, | ||
Adds a transformation to the transform chain. Transformations are central to the casting process, default transforms for each type coerce values to the specific type (as verified by [`isType()`](mixedistypevalue)). transforms are run before validations and only applied when `strict` is `true`. Some types have built in transformations. | ||
Adds a transformation to the transform chain. Transformations are central to the casting process, | ||
default transforms for each type coerce values to the specific type (as verified by [`isType()`](mixedistypevalue)). | ||
transforms are run before validations and only applied when `strict` is `true`. Some types have built in transformations. | ||
Transformations are useful for arbitrarily altering how the object is cast, __however, you should take care not to mutate the passed in value.__ Transforms are run sequentially so each `value` represents the current state of the cast, you can use the `orignalValue` param if you need to work on the raw initial value. | ||
Transformations are useful for arbitrarily altering how the object is cast, __however, you should take care | ||
not to mutate the passed in value.__ Transforms are run sequentially so each `value` represents the | ||
current state of the cast, you can use the `orignalValue` param if you need to work on the raw initial value. | ||
@@ -376,4 +430,4 @@ ```javascript | ||
return this.isType(value) && value !== null | ||
? value.toUpperCase() | ||
: value | ||
? value.toUpperCase() | ||
: value | ||
}); | ||
@@ -384,3 +438,5 @@ | ||
Each types will handle basic coercion of values to the proper type for you, but occasionally you may want to adjust or refine the default behavior. For example, if you wanted to use a different date parsing strategy than the default one you could do that with a transform. | ||
Each types will handle basic coercion of values to the proper type for you, but occasionally | ||
you may want to adjust or refine the default behavior. For example, if you wanted to use a different | ||
date parsing strategy than the default one you could do that with a transform. | ||
@@ -390,3 +446,3 @@ ```js | ||
//check to see if the previous transform already parsed the date | ||
if ( this.isType(value) ) return value | ||
if ( this.isType(value) ) return value | ||
@@ -412,3 +468,4 @@ //the default coercion failed so lets try it with Moment.js instead | ||
The same as the `mixed()` schema required, except that empty strings are also considered 'missing' values. To allow empty strings but fail on `undefined` values use: `string().required().min(0)` | ||
The same as the `mixed()` schema required, except that empty strings are also considered 'missing' values. | ||
To allow empty strings but fail on `undefined` values use: `string().required().min(0)` | ||
@@ -444,3 +501,3 @@ #### `string.min(Number limit, [String message])` | ||
Transforms string values by removing leading and trailing whitespace. If | ||
Transforms string values by removing leading and trailing whitespace. If | ||
`strict()` is set it will only validate that the value is trimmed. | ||
@@ -467,3 +524,3 @@ | ||
Set the minimum value allowed. The `${min}` interpolation can be used in the | ||
Set the minimum value allowed. The `${min}` interpolation can be used in the | ||
`message` argument. | ||
@@ -473,3 +530,3 @@ | ||
Set the maximum value allowed. The `${max}` interpolation can be used in the | ||
Set the maximum value allowed. The `${max}` interpolation can be used in the | ||
`message` argument. | ||
@@ -483,7 +540,7 @@ | ||
Value mut be a negative number. | ||
Value must be a negative number. | ||
#### `number.integer([String message])` | ||
Transformation that coerces the value into an integer via truncation | ||
Transformation that coerces the value into an integer via truncation | ||
` value | 0`. If `strict()` is set it will only validate that the value is an integer. | ||
@@ -507,3 +564,5 @@ | ||
Define a Date schema. By default ISO date strings will parse correctly, for more robust parsing options see the extending schema types at the end of the readme. Supports all the same methods as [`mixed`](#mixed). | ||
Define a Date schema. By default ISO date strings will parse correctly, | ||
for more robust parsing options see the extending schema types at the end of the readme. | ||
Supports all the same methods as [`mixed`](#mixed). | ||
@@ -525,3 +584,5 @@ ```javascript | ||
Define an array schema. Arrays can be typed or not, When specifying the element type, `cast` and `isValid` will apply to the elements as well. Options passed into `isValid` are passed also passed to child schemas. Supports all the same methods as [`mixed`](#mixed). | ||
Define an array schema. Arrays can be typed or not, When specifying the element type, `cast` and `isValid` | ||
will apply to the elements as well. Options passed into `isValid` are passed also passed to child schemas. | ||
Supports all the same methods as [`mixed`](#mixed). | ||
@@ -533,3 +594,3 @@ ```javascript | ||
schema.cast(['2', '3']) //=> [2, 3] | ||
schema.cast(['2', '3']) //=> [2, 3] | ||
``` | ||
@@ -539,7 +600,9 @@ | ||
Specify the schema of array elements. `of()` is optional and when ommited the array schema will not validate its contents. | ||
Specify the schema of array elements. `of()` is optional and when omitted the array schema will | ||
not validate its contents. | ||
#### `array.required([String message])` | ||
The same as the `mixed()` schema required, except that empty arrays are also considered 'missing' values. To allow empty arrays but fail on `undefined` values use: `array().required().min(0)` | ||
The same as the `mixed()` schema required, except that empty arrays are also considered 'missing' values. | ||
To allow empty arrays but fail on `undefined` values use: `array().required().min(0)` | ||
@@ -556,3 +619,3 @@ #### `array.min(Number limit, [String message])` | ||
Removes falsey values from the array. Providing a rejector function lets you specify the rejection criteria yourself. | ||
Removes falsey values from the array. Providing a rejecter function lets you specify the rejection criteria yourself. | ||
@@ -565,4 +628,4 @@ ```javascript | ||
array() | ||
.compact(function(v){ | ||
return v == null | ||
.compact(function(v){ | ||
return v == null | ||
}) | ||
@@ -574,3 +637,4 @@ .cast(['', 1, 0, 4, false, null]) // => ['',1, 0, 4, false] | ||
Define an object schema. Options passed into `isValid` are also passed to child schemas. Supports all the same methods as [`mixed`](#mixed). | ||
Define an object schema. Options passed into `isValid` are also passed to child schemas. | ||
Supports all the same methods as [`mixed`](#mixed). | ||
@@ -583,3 +647,3 @@ ```javascript | ||
website string().url(), | ||
}) | ||
}) | ||
``` | ||
@@ -610,3 +674,4 @@ | ||
Validate that teh object value only contains keys specified in `shape`, pass `false` as the first argument to disable the check. Restricting keys to known, also enables `stripUnknown` option, when not in strict mode. | ||
Validate that the object value only contains keys specified in `shape`, pass `false` as the first | ||
argument to disable the check. Restricting keys to known, also enables `stripUnknown` option, when not in strict mode. | ||
@@ -629,6 +694,6 @@ #### `object.camelcase()` | ||
var invalidDate = new Date(''); | ||
module.exports = yup.date() | ||
.transform(function(value, originalValue){ | ||
if ( this.isType(value) ) return value | ||
if ( this.isType(value) ) return value | ||
//the default coercion transform failed so lets try it with Moment instead | ||
@@ -640,8 +705,13 @@ value = Moment(originalValue, parseFormats) | ||
Alternatively, each schema is a normal javascript constructor function that you can mutate or delegate to using the normal patterns. Generally you should not inherit from `mixed` unless you know what you are doing, better to think of it as an abstract class. The other types are fair game though. | ||
Alternatively, each schema is a normal JavaScript constructor function that you can mutate or delegate to | ||
using the normal patterns. Generally you should not inherit from `mixed` unless you know what you are doing, | ||
better to think of it as an abstract class. The other types are fair game though. | ||
You should keep in mind some basic guidelines when extending schemas | ||
- never mutate an existing schema, always `clone()` and then mutate the new one before returning it. Built-in methods like `test` and `transform` take care of this for you, so you can safely use them (see below) without worrying | ||
- transforms should never mutate the `value` passed in, and should return an invalid object when one exists (`NaN`, `InvalidDate`, etc) instead of `null` for bad values. | ||
- by the time validations run the `value` is gaurunteed to be the correct type, however if `nullable` is set then `null` is a valid value for that type, so don't assume that a property or method exists on the value. | ||
- never mutate an existing schema, always `clone()` and then mutate the new one before returning it. | ||
Built-in methods like `test` and `transform` take care of this for you, so you can safely use them (see below) without worrying | ||
- transforms should never mutate the `value` passed in, and should return an invalid object when one exists | ||
(`NaN`, `InvalidDate`, etc) instead of `null` for bad values. | ||
- by the time validations run the `value` is guaranteed to be the correct type, however if `nullable` is | ||
set then `null` is a valid value for that type, so don't assume that a property or method exists on the value. | ||
@@ -654,7 +724,7 @@ __Adjust core Types__ | ||
function parseDateFromFormats(formats, parseStrict) { | ||
return this.transform(function(value, originalValue){ | ||
if ( this.isType(value) ) return value | ||
if ( this.isType(value) ) return value | ||
value = Moment(originalValue, formats, parseStrict) | ||
@@ -691,3 +761,3 @@ | ||
if ( this.isType(value) ) // we have a valid value | ||
return value | ||
return value | ||
value = Moment(originalValue, formats, strict) | ||
@@ -694,0 +764,0 @@ return value.isValid() ? value.toDate() : invalidDate |
@@ -49,3 +49,3 @@ 'use strict'; | ||
if( schema._type !== this._type ) | ||
if (schema._type !== this._type && this._type !== 'mixed') | ||
throw new TypeError(`You cannot \`concat()\` schema's of different types: ${this._type} and ${schema._type}`) | ||
@@ -56,3 +56,3 @@ | ||
// undefined isn't merged over, but is a valid value for default | ||
if( schema._default === undefined && _.has(this, '_default') ) | ||
if (schema._default === undefined && _.has(this, '_default')) | ||
next._default = schema._default | ||
@@ -64,2 +64,4 @@ | ||
next._type = schema._type; | ||
return next | ||
@@ -74,3 +76,3 @@ }, | ||
cast(_value, _opts) { | ||
var schema = this._resolve((_opts|| {}).context) | ||
var schema = this._resolve((_opts || {}).context) | ||
return schema._cast(_value, _opts) | ||
@@ -219,3 +221,3 @@ }, | ||
, next = this.clone() | ||
, errorMsg, isExclusive; | ||
, isExclusive; | ||
@@ -222,0 +224,0 @@ if (typeof name === 'string') { |
@@ -27,4 +27,4 @@ 'use strict'; | ||
if( options.then && options.then._type !== type || options.otherwise && options.otherwise._type !== type) | ||
throw new TypeError(`cannot create polymorphic conditionals, \`then\` and \`otherwise\` must be the same type: ${type}`) | ||
// if( options.then && options.then._type !== type || options.otherwise && options.otherwise._type !== type) | ||
// throw new TypeError(`cannot create polymorphic conditionals, \`then\` and \`otherwise\` must be the same type: ${type}`) | ||
@@ -57,2 +57,2 @@ is = typeof is === 'function' | ||
module.exports = Conditional; | ||
module.exports = Conditional; |
@@ -108,3 +108,3 @@ 'use strict'; | ||
it('exclusive tests should throw without a name', function(){ | ||
;(function(){ | ||
(function(){ | ||
mixed().test({ message: 'invalid', exclusive: true, test: function(){} }) | ||
@@ -137,3 +137,3 @@ }).should.throw() | ||
name: 'max', | ||
test: function(v, path, context){ | ||
test: function(){ | ||
this.path.should.equal('test') | ||
@@ -154,3 +154,3 @@ this.parent.should.eql({ other: 5, test : 'hi' }) | ||
name: 'max', | ||
test: function(v){ | ||
test: function(){ | ||
return this.createError({ path: 'my.path' }) | ||
@@ -172,3 +172,3 @@ } | ||
name: 'max', | ||
test: function(v){ | ||
test: function(){ | ||
return this.createError({ message: '${path} nope!', path: 'my.path' }) | ||
@@ -261,5 +261,5 @@ } | ||
it('concat should fail on different types', function(){ | ||
var inst = string().default('hi') | ||
var inst = string().default('hi'); | ||
;(function(){ | ||
(function(){ | ||
inst.concat(object()) | ||
@@ -269,2 +269,11 @@ }).should.throw(TypeError) | ||
it('concat should allow mixed and other type', function(){ | ||
var inst = mixed().default('hi'); | ||
(function(){ | ||
inst.concat(string())._type.should.equal('string') | ||
}).should.not.throw(TypeError) | ||
}) | ||
it('concat should maintain undefined defaults', function(){ | ||
@@ -294,3 +303,3 @@ var inst = string().default('hi') | ||
inst._validate(undefined, {}, { parent: { prop: 1 }}).should.be.fulfilled, | ||
inst._validate('hello', {}, { parent: { prop: 5 }}).should.be.fulfilled, | ||
inst._validate('hello', {}, { parent: { prop: 5 }}).should.be.fulfilled | ||
]) | ||
@@ -346,4 +355,1 @@ .then(function(){ | ||
}) | ||
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
167701
3562
732
23