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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ $ npm install parameter --save
- `constructor([options])` - new Class `Parameter` instance
- `options.translate` - translate function
- `validate(rule, value)` - validate the `value` conforms to `rule`. return an array of errors if break rule.
- `validateWithTranslate(rule, value, translate)` - validate the `value` conforms to `rule`, with customize translate method.
- `addRule(type, check)` - add custom rules.
- `type` - rule type, required and must be string type.
- `check` - check handler. can be a `function` or a `RegExp`.
Expand Down
23 changes: 22 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,13 +49,34 @@ class Parameter {
}
}

/**
* validate with customize translate
*
* @param {Object} rules
* @param {Mixed} obj
* @param {Function} translate
* @return {Object} errors
* @api public
*/
validateWithTranslate(rules, obj, translate) {
var _translate = this.translate;
this.translate = translate;
try {
return this.validate(rules, obj);
} finally {
this.translate = _translate;
}
};

/**
* validate
*
* @param {Object} rules
* @return {Object} obj
* @param {Mixed} obj
* @return {Object} errors
* @api public
*/

validate(rules, obj) {
if (typeof rules !== 'object') {
throw new TypeError('need object type rule');
Expand Down
36 changes: 36 additions & 0 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -594,4 +594,40 @@ describe('parameter', function () {
error.field.should.equal('name');
});
});

describe('validateWithTranslate()', function() {
it('should work', function() {
var translate = function() {
var args = Array.prototype.slice.call(arguments);
args[0] = args[0] + '-add.';
return util.format.apply(util, args);
};

var p1 = new Parameter();

var rule = { name: 'string' };
var error = p1.validateWithTranslate(rule, {}, translate)[0];
error.message.should.equal('required-add.');
error.code.should.equal('missing_field-add.');
error.field.should.equal('name');
});

it('should reset translate', function(done) {
var translate = function() {
var args = Array.prototype.slice.call(arguments);
args[0] = args[0] + '-add.';
return util.format.apply(util, args);
};

var p1 = new Parameter();

var rule = { name: 'invalid' };
try {
p1.validateWithTranslate(rule, {name: 1}, translate);
} catch (e) {
should.not.exist(p1.translate);
done();
}
});
});
});