Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extend the supported data types using types option #127

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
4 changes: 4 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
13 changes: 13 additions & 0 deletions test/misc.js
Original file line number Diff line number Diff line change
Expand Up @@ -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()
})