From a6a50758c5fa3b69e250e3219d9514bf00dc0992 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=8D=E5=9B=9B?= Date: Wed, 27 Jan 2016 15:22:57 +0800 Subject: [PATCH] feat: support validateWithTranslate --- README.md | 1 + index.js | 23 ++++++++++++++++++++++- test/index.test.js | 36 ++++++++++++++++++++++++++++++++++++ 3 files changed, 59 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 2224876..59df009 100644 --- a/README.md +++ b/README.md @@ -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`. diff --git a/index.js b/index.js index ee48d0b..a420b54 100644 --- a/index.js +++ b/index.js @@ -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'); diff --git a/test/index.test.js b/test/index.test.js index dc6c6b9..a72d4fd 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -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(); + } + }); + }); });