Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,14 @@ The `Array.of` method has three signatures:

### Functions ###

`Function.reference(func)` matches `x` if `x === func`.
The `Function.reference(func)` matches `x` if `x === func`.

The `Function.custom(func)` takes a user-defined function and passes `x` to it. The user-defined function must return `{valid: myBooleanValue, msg: 'My fail message'}` where the `valid` field tells js-schema to pass or fail the test, and `msg` is the error message shown if `valid` is `false`. For example:
```javascript
var validate = schema({
 'name': Function.custom(x => ( { valid: x !== 'Bob' && x.length < 4, msg: 'Name is Bob or is too long' } ))
});
```

Future plans
============
Expand Down
1 change: 1 addition & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
module.exports = require('./lib/schema')

// Patterns
require('./lib/patterns/custom')
require('./lib/patterns/reference')
require('./lib/patterns/nothing')
require('./lib/patterns/anything')
Expand Down
9 changes: 7 additions & 2 deletions lib/extensions/Function.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
var ReferenceSchema = require('../patterns/reference')
var CustomSchema = require('../patterns/custom')

Function.reference = function(f) {
return new ReferenceSchema(f).wrap()
Function.reference = function (f) {
return new ReferenceSchema(f).wrap()
}

Function.custom = function (f) {
return new CustomSchema(f).wrap()
}
25 changes: 25 additions & 0 deletions lib/patterns/custom.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
var Schema = require('../BaseSchema')

var CustomSchema = module.exports = Schema.patterns.CustomSchema = Schema.extend({
initialize: function (func) {
this.func = func
},
errors: function (instance) {
var self = this
var result = self.func(instance);

if (!result.valid)
return result.msg
return false
},
validate: function (instance) {
return this.func(instance).valid
},
toJSON: function () {
return { type: 'custom' }
}
})

Schema.fromJS.def(function (func) {
return new CustomSchema(func)
})