Skip to content

Commit

Permalink
Add custom message error for required fields
Browse files Browse the repository at this point in the history
  • Loading branch information
Kikobeats committed Apr 6, 2016
1 parent aa20700 commit 5b8923c
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 5 deletions.
12 changes: 7 additions & 5 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@
// }
// })

// TODO: Add strict mode

var isFunction = require('lodash/isfunction')
var isArray = require('lodash/isArray')
var isString = require('lodash/isString')
var reduce = require('lodash/reduce')
var assign = require('lodash/assign')
var flow = require('lodash/flow')
Expand All @@ -47,8 +47,10 @@ function addRule (schema, blueprint, name) {
return schema
}

function throwError (name, type) {
var msg = 'Need to provide {' + type + "} for '" + name + "' field."
function throwError (name, type, required) {
var msg
if (isArray(required) && isString(required[1])) msg = required[1]
else msg = 'Need to provide {' + type + "} for '" + name + "' field."
var err = ENOTYPE(msg)
throw err
}
Expand All @@ -75,7 +77,7 @@ function Ardent (schemaBlueprint) {
var applyFilters = flow(rule.filter)
var hasValue = exists(obj[name])

if (rule.required && !hasValue) throwError(name, schemaTypes[name])
if (rule.required && !hasValue) throwError(name, schemaTypes[name], rule.required)

var value

Expand Down
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,9 @@
"chaste": "~1.1.0",
"lodash.assign": "~4.0.7",
"lodash.flow": "~3.2.1",
"lodash.isarray": "~4.0.0",
"lodash.isfunction": "~3.0.8",
"lodash.isstring": "~4.0.1",
"lodash.reduce": "~4.3.0",
"whoops": "~2.0.1"
},
Expand Down
13 changes: 13 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,5 +65,18 @@ describe('schema defintion', function () {
var errMessage = "Need to provide {String} for 'age' field."
;(function () { ardent() }).should.throw(errMessage)
})

it('custom error message', function () {
var schema = {
age: {
type: String,
required: [true, 'your message here']
}
}

var ardent = Ardent(schema)
var errMessage = 'your message here'
;(function () { ardent() }).should.throw(errMessage)
})
})
})

0 comments on commit 5b8923c

Please sign in to comment.