diff --git a/README.md b/README.md index e3963f6..dba80d0 100644 --- a/README.md +++ b/README.md @@ -154,6 +154,23 @@ console.log(validate.errors) // [{field: 'data.y', message: 'is required'}, // {field: 'data.x', message: 'is the wrong type'}] ``` +## Extend the supported data types using `types` option + +Add additional types (or extend the default types) by specifying the `types` option. For example if you need to add a validator function for type `file` (Swagger has a data type file), define file validator function as an `option` to validator. + +```js +var schema = { type: 'file' } +var validate = validator(schema, { + types: { + file: function (filename) { + return 'typeof '+filename+' === "string"'; + } + } +}); +validate('somefile.txt'); + +``` + ## Error messages Here is a list of possible `message` values for errors: diff --git a/index.js b/index.js index 427f750..97e150f 100644 --- a/index.js +++ b/index.js @@ -110,6 +110,10 @@ var isMultipleOf = function(name, multipleOf) { } var compile = function(schema, cache, root, reporter, opts) { + //Extend the types + if (opts && opts.types) { + types = xtend(types, opts.types); + } var fmts = opts ? xtend(formats, opts.formats) : formats var scope = {unique:unique, formats:fmts, isMultipleOf:isMultipleOf} var verbose = opts ? !!opts.verbose : false; diff --git a/test/misc.js b/test/misc.js index 4ea36d5..2bf978d 100644 --- a/test/misc.js +++ b/test/misc.js @@ -469,3 +469,16 @@ tape('field shows item index in arrays', function(t) { t.strictEqual(validate.errors[0].field, 'data.1.1.foo', 'should output the field with specific index of failing item in the error') t.end() }) + +tape('Extend types', function(t) { + var schema = { type: 'file' } + var validate = validator(schema, { + types: { + file: function (filename) { + return 'typeof '+filename+' === "string"'; + } + } + }); + t.ok(validate('somefile.text'), 'is file') + t.end() +})