index.js 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. 'use strict';
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. var _extends2 = require('babel-runtime/helpers/extends');
  6. var _extends3 = _interopRequireDefault(_extends2);
  7. var _typeof2 = require('babel-runtime/helpers/typeof');
  8. var _typeof3 = _interopRequireDefault(_typeof2);
  9. var _util = require('./util');
  10. var _validator = require('./validator/');
  11. var _validator2 = _interopRequireDefault(_validator);
  12. var _messages2 = require('./messages');
  13. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  14. /**
  15. * Encapsulates a validation schema.
  16. *
  17. * @param descriptor An object declaring validation rules
  18. * for this schema.
  19. */
  20. function Schema(descriptor) {
  21. this.rules = null;
  22. this._messages = _messages2.messages;
  23. this.define(descriptor);
  24. }
  25. Schema.prototype = {
  26. messages: function messages(_messages) {
  27. if (_messages) {
  28. this._messages = (0, _util.deepMerge)((0, _messages2.newMessages)(), _messages);
  29. }
  30. return this._messages;
  31. },
  32. define: function define(rules) {
  33. if (!rules) {
  34. throw new Error('Cannot configure a schema with no rules');
  35. }
  36. if ((typeof rules === 'undefined' ? 'undefined' : (0, _typeof3['default'])(rules)) !== 'object' || Array.isArray(rules)) {
  37. throw new Error('Rules must be an object');
  38. }
  39. this.rules = {};
  40. var z = void 0;
  41. var item = void 0;
  42. for (z in rules) {
  43. if (rules.hasOwnProperty(z)) {
  44. item = rules[z];
  45. this.rules[z] = Array.isArray(item) ? item : [item];
  46. }
  47. }
  48. },
  49. validate: function validate(source_) {
  50. var _this = this;
  51. var o = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  52. var oc = arguments[2];
  53. var source = source_;
  54. var options = o;
  55. var callback = oc;
  56. if (typeof options === 'function') {
  57. callback = options;
  58. options = {};
  59. }
  60. if (!this.rules || Object.keys(this.rules).length === 0) {
  61. if (callback) {
  62. callback();
  63. }
  64. return;
  65. }
  66. function complete(results) {
  67. var i = void 0;
  68. var field = void 0;
  69. var errors = [];
  70. var fields = {};
  71. function add(e) {
  72. if (Array.isArray(e)) {
  73. errors = errors.concat.apply(errors, e);
  74. } else {
  75. errors.push(e);
  76. }
  77. }
  78. for (i = 0; i < results.length; i++) {
  79. add(results[i]);
  80. }
  81. if (!errors.length) {
  82. errors = null;
  83. fields = null;
  84. } else {
  85. for (i = 0; i < errors.length; i++) {
  86. field = errors[i].field;
  87. fields[field] = fields[field] || [];
  88. fields[field].push(errors[i]);
  89. }
  90. }
  91. callback(errors, fields);
  92. }
  93. if (options.messages) {
  94. var messages = this.messages();
  95. if (messages === _messages2.messages) {
  96. messages = (0, _messages2.newMessages)();
  97. }
  98. (0, _util.deepMerge)(messages, options.messages);
  99. options.messages = messages;
  100. } else {
  101. options.messages = this.messages();
  102. }
  103. var arr = void 0;
  104. var value = void 0;
  105. var series = {};
  106. var keys = options.keys || Object.keys(this.rules);
  107. keys.forEach(function (z) {
  108. arr = _this.rules[z];
  109. value = source[z];
  110. arr.forEach(function (r) {
  111. var rule = r;
  112. if (typeof rule.transform === 'function') {
  113. if (source === source_) {
  114. source = (0, _extends3['default'])({}, source);
  115. }
  116. value = source[z] = rule.transform(value);
  117. }
  118. if (typeof rule === 'function') {
  119. rule = {
  120. validator: rule
  121. };
  122. } else {
  123. rule = (0, _extends3['default'])({}, rule);
  124. }
  125. rule.validator = _this.getValidationMethod(rule);
  126. rule.field = z;
  127. rule.fullField = rule.fullField || z;
  128. rule.type = _this.getType(rule);
  129. if (!rule.validator) {
  130. return;
  131. }
  132. series[z] = series[z] || [];
  133. series[z].push({
  134. rule: rule,
  135. value: value,
  136. source: source,
  137. field: z
  138. });
  139. });
  140. });
  141. var errorFields = {};
  142. (0, _util.asyncMap)(series, options, function (data, doIt) {
  143. var rule = data.rule;
  144. var deep = (rule.type === 'object' || rule.type === 'array') && ((0, _typeof3['default'])(rule.fields) === 'object' || (0, _typeof3['default'])(rule.defaultField) === 'object');
  145. deep = deep && (rule.required || !rule.required && data.value);
  146. rule.field = data.field;
  147. function addFullfield(key, schema) {
  148. return (0, _extends3['default'])({}, schema, {
  149. fullField: rule.fullField + '.' + key
  150. });
  151. }
  152. function cb() {
  153. var e = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  154. var errors = e;
  155. if (!Array.isArray(errors)) {
  156. errors = [errors];
  157. }
  158. if (errors.length) {
  159. (0, _util.warning)('async-validator:', errors);
  160. }
  161. if (errors.length && rule.message) {
  162. errors = [].concat(rule.message);
  163. }
  164. errors = errors.map((0, _util.complementError)(rule));
  165. if (options.first && errors.length) {
  166. errorFields[rule.field] = 1;
  167. return doIt(errors);
  168. }
  169. if (!deep) {
  170. doIt(errors);
  171. } else {
  172. // if rule is required but the target object
  173. // does not exist fail at the rule level and don't
  174. // go deeper
  175. if (rule.required && !data.value) {
  176. if (rule.message) {
  177. errors = [].concat(rule.message).map((0, _util.complementError)(rule));
  178. } else if (options.error) {
  179. errors = [options.error(rule, (0, _util.format)(options.messages.required, rule.field))];
  180. } else {
  181. errors = [];
  182. }
  183. return doIt(errors);
  184. }
  185. var fieldsSchema = {};
  186. if (rule.defaultField) {
  187. for (var k in data.value) {
  188. if (data.value.hasOwnProperty(k)) {
  189. fieldsSchema[k] = rule.defaultField;
  190. }
  191. }
  192. }
  193. fieldsSchema = (0, _extends3['default'])({}, fieldsSchema, data.rule.fields);
  194. for (var f in fieldsSchema) {
  195. if (fieldsSchema.hasOwnProperty(f)) {
  196. var fieldSchema = Array.isArray(fieldsSchema[f]) ? fieldsSchema[f] : [fieldsSchema[f]];
  197. fieldsSchema[f] = fieldSchema.map(addFullfield.bind(null, f));
  198. }
  199. }
  200. var schema = new Schema(fieldsSchema);
  201. schema.messages(options.messages);
  202. if (data.rule.options) {
  203. data.rule.options.messages = options.messages;
  204. data.rule.options.error = options.error;
  205. }
  206. schema.validate(data.value, data.rule.options || options, function (errs) {
  207. doIt(errs && errs.length ? errors.concat(errs) : errs);
  208. });
  209. }
  210. }
  211. var res = rule.validator(rule, data.value, cb, data.source, options);
  212. if (res && res.then) {
  213. res.then(function () {
  214. return cb();
  215. }, function (e) {
  216. return cb(e);
  217. });
  218. }
  219. }, function (results) {
  220. complete(results);
  221. });
  222. },
  223. getType: function getType(rule) {
  224. if (rule.type === undefined && rule.pattern instanceof RegExp) {
  225. rule.type = 'pattern';
  226. }
  227. if (typeof rule.validator !== 'function' && rule.type && !_validator2['default'].hasOwnProperty(rule.type)) {
  228. throw new Error((0, _util.format)('Unknown rule type %s', rule.type));
  229. }
  230. return rule.type || 'string';
  231. },
  232. getValidationMethod: function getValidationMethod(rule) {
  233. if (typeof rule.validator === 'function') {
  234. return rule.validator;
  235. }
  236. var keys = Object.keys(rule);
  237. var messageIndex = keys.indexOf('message');
  238. if (messageIndex !== -1) {
  239. keys.splice(messageIndex, 1);
  240. }
  241. if (keys.length === 1 && keys[0] === 'required') {
  242. return _validator2['default'].required;
  243. }
  244. return _validator2['default'][this.getType(rule)] || false;
  245. }
  246. };
  247. Schema.register = function register(type, validator) {
  248. if (typeof validator !== 'function') {
  249. throw new Error('Cannot register a validator by type, validator is not a function');
  250. }
  251. _validator2['default'][type] = validator;
  252. };
  253. Schema.messages = _messages2.messages;
  254. exports['default'] = Schema;
  255. module.exports = exports['default'];