async-validator.js 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362
  1. function _extends() {
  2. _extends = Object.assign || function (target) {
  3. for (var i = 1; i < arguments.length; i++) {
  4. var source = arguments[i];
  5. for (var key in source) {
  6. if (Object.prototype.hasOwnProperty.call(source, key)) {
  7. target[key] = source[key];
  8. }
  9. }
  10. }
  11. return target;
  12. };
  13. return _extends.apply(this, arguments);
  14. }
  15. /* eslint no-console:0 */
  16. var formatRegExp = /%[sdj%]/g;
  17. var warning = function warning() {
  18. }; // don't print warning message when in production env or node runtime
  19. if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV !== 'production' && typeof window !==
  20. 'undefined' && typeof document !== 'undefined') {
  21. warning = function warning(type, errors) {
  22. if (typeof console !== 'undefined' && console.warn) {
  23. if (errors.every(function (e) {
  24. return typeof e === 'string';
  25. })) {
  26. console.warn(type, errors);
  27. }
  28. }
  29. };
  30. }
  31. function convertFieldsError(errors) {
  32. if (!errors || !errors.length) return null;
  33. var fields = {};
  34. errors.forEach(function (error) {
  35. var field = error.field;
  36. fields[field] = fields[field] || [];
  37. fields[field].push(error);
  38. });
  39. return fields;
  40. }
  41. function format() {
  42. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  43. args[_key] = arguments[_key];
  44. }
  45. var i = 1;
  46. var f = args[0];
  47. var len = args.length;
  48. if (typeof f === 'function') {
  49. return f.apply(null, args.slice(1));
  50. }
  51. if (typeof f === 'string') {
  52. var str = String(f).replace(formatRegExp, function (x) {
  53. if (x === '%%') {
  54. return '%';
  55. }
  56. if (i >= len) {
  57. return x;
  58. }
  59. switch (x) {
  60. case '%s':
  61. return String(args[i++]);
  62. case '%d':
  63. return Number(args[i++]);
  64. case '%j':
  65. try {
  66. return JSON.stringify(args[i++]);
  67. } catch (_) {
  68. return '[Circular]';
  69. }
  70. break;
  71. default:
  72. return x;
  73. }
  74. });
  75. for (var arg = args[i]; i < len; arg = args[++i]) {
  76. str += " " + arg;
  77. }
  78. return str;
  79. }
  80. return f;
  81. }
  82. function isNativeStringType(type) {
  83. return type === 'string' || type === 'url' || type === 'hex' || type === 'email' || type === 'pattern';
  84. }
  85. function isEmptyValue(value, type) {
  86. if (value === undefined || value === null) {
  87. return true;
  88. }
  89. if (type === 'array' && Array.isArray(value) && !value.length) {
  90. return true;
  91. }
  92. if (isNativeStringType(type) && typeof value === 'string' && !value) {
  93. return true;
  94. }
  95. return false;
  96. }
  97. function asyncParallelArray(arr, func, callback) {
  98. var results = [];
  99. var total = 0;
  100. var arrLength = arr.length;
  101. function count(errors) {
  102. results.push.apply(results, errors);
  103. total++;
  104. if (total === arrLength) {
  105. callback(results);
  106. }
  107. }
  108. arr.forEach(function (a) {
  109. func(a, count);
  110. });
  111. }
  112. function asyncSerialArray(arr, func, callback) {
  113. var index = 0;
  114. var arrLength = arr.length;
  115. function next(errors) {
  116. if (errors && errors.length) {
  117. callback(errors);
  118. return;
  119. }
  120. var original = index;
  121. index = index + 1;
  122. if (original < arrLength) {
  123. func(arr[original], next);
  124. } else {
  125. callback([]);
  126. }
  127. }
  128. next([]);
  129. }
  130. function flattenObjArr(objArr) {
  131. var ret = [];
  132. Object.keys(objArr).forEach(function (k) {
  133. ret.push.apply(ret, objArr[k]);
  134. });
  135. return ret;
  136. }
  137. function asyncMap(objArr, option, func, callback) {
  138. if (option.first) {
  139. var _pending = new Promise(function (resolve, reject) {
  140. var next = function next(errors) {
  141. callback(errors);
  142. return errors.length ? reject({
  143. errors: errors,
  144. fields: convertFieldsError(errors)
  145. }) : resolve();
  146. };
  147. var flattenArr = flattenObjArr(objArr);
  148. asyncSerialArray(flattenArr, func, next);
  149. });
  150. _pending["catch"](function (e) {
  151. return e;
  152. });
  153. return _pending;
  154. }
  155. var firstFields = option.firstFields || [];
  156. if (firstFields === true) {
  157. firstFields = Object.keys(objArr);
  158. }
  159. var objArrKeys = Object.keys(objArr);
  160. var objArrLength = objArrKeys.length;
  161. var total = 0;
  162. var results = [];
  163. var pending = new Promise(function (resolve, reject) {
  164. var next = function next(errors) {
  165. results.push.apply(results, errors);
  166. total++;
  167. if (total === objArrLength) {
  168. callback(results);
  169. return results.length ? reject({
  170. errors: results,
  171. fields: convertFieldsError(results)
  172. }) : resolve();
  173. }
  174. };
  175. if (!objArrKeys.length) {
  176. callback(results);
  177. resolve();
  178. }
  179. objArrKeys.forEach(function (key) {
  180. var arr = objArr[key];
  181. if (firstFields.indexOf(key) !== -1) {
  182. asyncSerialArray(arr, func, next);
  183. } else {
  184. asyncParallelArray(arr, func, next);
  185. }
  186. });
  187. });
  188. pending["catch"](function (e) {
  189. return e;
  190. });
  191. return pending;
  192. }
  193. function complementError(rule) {
  194. return function (oe) {
  195. if (oe && oe.message) {
  196. oe.field = oe.field || rule.fullField;
  197. return oe;
  198. }
  199. return {
  200. message: typeof oe === 'function' ? oe() : oe,
  201. field: oe.field || rule.fullField
  202. };
  203. };
  204. }
  205. function deepMerge(target, source) {
  206. if (source) {
  207. for (var s in source) {
  208. if (source.hasOwnProperty(s)) {
  209. var value = source[s];
  210. if (typeof value === 'object' && typeof target[s] === 'object') {
  211. target[s] = _extends({}, target[s], {}, value);
  212. } else {
  213. target[s] = value;
  214. }
  215. }
  216. }
  217. }
  218. return target;
  219. }
  220. /**
  221. * Rule for validating required fields.
  222. *
  223. * @param rule The validation rule.
  224. * @param value The value of the field on the source object.
  225. * @param source The source object being validated.
  226. * @param errors An array of errors that this rule may add
  227. * validation errors to.
  228. * @param options The validation options.
  229. * @param options.messages The validation messages.
  230. */
  231. function required(rule, value, source, errors, options, type) {
  232. if (rule.required && (!source.hasOwnProperty(rule.field) || isEmptyValue(value, type || rule.type))) {
  233. errors.push(format(options.messages.required, rule.fullField));
  234. }
  235. }
  236. /**
  237. * Rule for validating whitespace.
  238. *
  239. * @param rule The validation rule.
  240. * @param value The value of the field on the source object.
  241. * @param source The source object being validated.
  242. * @param errors An array of errors that this rule may add
  243. * validation errors to.
  244. * @param options The validation options.
  245. * @param options.messages The validation messages.
  246. */
  247. function whitespace(rule, value, source, errors, options) {
  248. if (/^\s+$/.test(value) || value === '') {
  249. errors.push(format(options.messages.whitespace, rule.fullField));
  250. }
  251. }
  252. /* eslint max-len:0 */
  253. var pattern = {
  254. // http://emailregex.com/
  255. email: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
  256. url: new RegExp(
  257. "^(?!mailto:)(?:(?:http|https|ftp)://|//)(?:\\S+(?::\\S*)?@)?(?:(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-*)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-*)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))|localhost)(?::\\d{2,5})?(?:(/|\\?|#)[^\\s]*)?$",
  258. 'i'),
  259. hex: /^#?([a-f0-9]{6}|[a-f0-9]{3})$/i
  260. };
  261. var types = {
  262. integer: function integer(value) {
  263. return types.number(value) && parseInt(value, 10) === value;
  264. },
  265. "float": function float(value) {
  266. return types.number(value) && !types.integer(value);
  267. },
  268. array: function array(value) {
  269. return Array.isArray(value);
  270. },
  271. regexp: function regexp(value) {
  272. if (value instanceof RegExp) {
  273. return true;
  274. }
  275. try {
  276. return !!new RegExp(value);
  277. } catch (e) {
  278. return false;
  279. }
  280. },
  281. date: function date(value) {
  282. return typeof value.getTime === 'function' && typeof value.getMonth === 'function' && typeof value.getYear ===
  283. 'function';
  284. },
  285. number: function number(value) {
  286. if (isNaN(value)) {
  287. return false;
  288. }
  289. // 修改源码,将字符串数值先转为数值
  290. return typeof +value === 'number';
  291. },
  292. object: function object(value) {
  293. return typeof value === 'object' && !types.array(value);
  294. },
  295. method: function method(value) {
  296. return typeof value === 'function';
  297. },
  298. email: function email(value) {
  299. return typeof value === 'string' && !!value.match(pattern.email) && value.length < 255;
  300. },
  301. url: function url(value) {
  302. return typeof value === 'string' && !!value.match(pattern.url);
  303. },
  304. hex: function hex(value) {
  305. return typeof value === 'string' && !!value.match(pattern.hex);
  306. }
  307. };
  308. /**
  309. * Rule for validating the type of a value.
  310. *
  311. * @param rule The validation rule.
  312. * @param value The value of the field on the source object.
  313. * @param source The source object being validated.
  314. * @param errors An array of errors that this rule may add
  315. * validation errors to.
  316. * @param options The validation options.
  317. * @param options.messages The validation messages.
  318. */
  319. function type(rule, value, source, errors, options) {
  320. if (rule.required && value === undefined) {
  321. required(rule, value, source, errors, options);
  322. return;
  323. }
  324. var custom = ['integer', 'float', 'array', 'regexp', 'object', 'method', 'email', 'number', 'date', 'url', 'hex'];
  325. var ruleType = rule.type;
  326. if (custom.indexOf(ruleType) > -1) {
  327. if (!types[ruleType](value)) {
  328. errors.push(format(options.messages.types[ruleType], rule.fullField, rule.type));
  329. } // straight typeof check
  330. } else if (ruleType && typeof value !== rule.type) {
  331. errors.push(format(options.messages.types[ruleType], rule.fullField, rule.type));
  332. }
  333. }
  334. /**
  335. * Rule for validating minimum and maximum allowed values.
  336. *
  337. * @param rule The validation rule.
  338. * @param value The value of the field on the source object.
  339. * @param source The source object being validated.
  340. * @param errors An array of errors that this rule may add
  341. * validation errors to.
  342. * @param options The validation options.
  343. * @param options.messages The validation messages.
  344. */
  345. function range(rule, value, source, errors, options) {
  346. var len = typeof rule.len === 'number';
  347. var min = typeof rule.min === 'number';
  348. var max = typeof rule.max === 'number'; // 正则匹配码点范围从U+010000一直到U+10FFFF的文字(补充平面Supplementary Plane)
  349. var spRegexp = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
  350. var val = value;
  351. var key = null;
  352. var num = typeof value === 'number';
  353. var str = typeof value === 'string';
  354. var arr = Array.isArray(value);
  355. if (num) {
  356. key = 'number';
  357. } else if (str) {
  358. key = 'string';
  359. } else if (arr) {
  360. key = 'array';
  361. } // if the value is not of a supported type for range validation
  362. // the validation rule rule should use the
  363. // type property to also test for a particular type
  364. if (!key) {
  365. return false;
  366. }
  367. if (arr) {
  368. val = value.length;
  369. }
  370. if (str) {
  371. // 处理码点大于U+010000的文字length属性不准确的bug,如"𠮷𠮷𠮷".lenght !== 3
  372. val = value.replace(spRegexp, '_').length;
  373. }
  374. if (len) {
  375. if (val !== rule.len) {
  376. errors.push(format(options.messages[key].len, rule.fullField, rule.len));
  377. }
  378. } else if (min && !max && val < rule.min) {
  379. errors.push(format(options.messages[key].min, rule.fullField, rule.min));
  380. } else if (max && !min && val > rule.max) {
  381. errors.push(format(options.messages[key].max, rule.fullField, rule.max));
  382. } else if (min && max && (val < rule.min || val > rule.max)) {
  383. errors.push(format(options.messages[key].range, rule.fullField, rule.min, rule.max));
  384. }
  385. }
  386. var ENUM = 'enum';
  387. /**
  388. * Rule for validating a value exists in an enumerable list.
  389. *
  390. * @param rule The validation rule.
  391. * @param value The value of the field on the source object.
  392. * @param source The source object being validated.
  393. * @param errors An array of errors that this rule may add
  394. * validation errors to.
  395. * @param options The validation options.
  396. * @param options.messages The validation messages.
  397. */
  398. function enumerable(rule, value, source, errors, options) {
  399. rule[ENUM] = Array.isArray(rule[ENUM]) ? rule[ENUM] : [];
  400. if (rule[ENUM].indexOf(value) === -1) {
  401. errors.push(format(options.messages[ENUM], rule.fullField, rule[ENUM].join(', ')));
  402. }
  403. }
  404. /**
  405. * Rule for validating a regular expression pattern.
  406. *
  407. * @param rule The validation rule.
  408. * @param value The value of the field on the source object.
  409. * @param source The source object being validated.
  410. * @param errors An array of errors that this rule may add
  411. * validation errors to.
  412. * @param options The validation options.
  413. * @param options.messages The validation messages.
  414. */
  415. function pattern$1(rule, value, source, errors, options) {
  416. if (rule.pattern) {
  417. if (rule.pattern instanceof RegExp) {
  418. // if a RegExp instance is passed, reset `lastIndex` in case its `global`
  419. // flag is accidentally set to `true`, which in a validation scenario
  420. // is not necessary and the result might be misleading
  421. rule.pattern.lastIndex = 0;
  422. if (!rule.pattern.test(value)) {
  423. errors.push(format(options.messages.pattern.mismatch, rule.fullField, value, rule.pattern));
  424. }
  425. } else if (typeof rule.pattern === 'string') {
  426. var _pattern = new RegExp(rule.pattern);
  427. if (!_pattern.test(value)) {
  428. errors.push(format(options.messages.pattern.mismatch, rule.fullField, value, rule.pattern));
  429. }
  430. }
  431. }
  432. }
  433. var rules = {
  434. required: required,
  435. whitespace: whitespace,
  436. type: type,
  437. range: range,
  438. "enum": enumerable,
  439. pattern: pattern$1
  440. };
  441. /**
  442. * Performs validation for string types.
  443. *
  444. * @param rule The validation rule.
  445. * @param value The value of the field on the source object.
  446. * @param callback The callback function.
  447. * @param source The source object being validated.
  448. * @param options The validation options.
  449. * @param options.messages The validation messages.
  450. */
  451. function string(rule, value, callback, source, options) {
  452. var errors = [];
  453. var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
  454. if (validate) {
  455. if (isEmptyValue(value, 'string') && !rule.required) {
  456. return callback();
  457. }
  458. rules.required(rule, value, source, errors, options, 'string');
  459. if (!isEmptyValue(value, 'string')) {
  460. rules.type(rule, value, source, errors, options);
  461. rules.range(rule, value, source, errors, options);
  462. rules.pattern(rule, value, source, errors, options);
  463. if (rule.whitespace === true) {
  464. rules.whitespace(rule, value, source, errors, options);
  465. }
  466. }
  467. }
  468. callback(errors);
  469. }
  470. /**
  471. * Validates a function.
  472. *
  473. * @param rule The validation rule.
  474. * @param value The value of the field on the source object.
  475. * @param callback The callback function.
  476. * @param source The source object being validated.
  477. * @param options The validation options.
  478. * @param options.messages The validation messages.
  479. */
  480. function method(rule, value, callback, source, options) {
  481. var errors = [];
  482. var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
  483. if (validate) {
  484. if (isEmptyValue(value) && !rule.required) {
  485. return callback();
  486. }
  487. rules.required(rule, value, source, errors, options);
  488. if (value !== undefined) {
  489. rules.type(rule, value, source, errors, options);
  490. }
  491. }
  492. callback(errors);
  493. }
  494. /**
  495. * Validates a number.
  496. *
  497. * @param rule The validation rule.
  498. * @param value The value of the field on the source object.
  499. * @param callback The callback function.
  500. * @param source The source object being validated.
  501. * @param options The validation options.
  502. * @param options.messages The validation messages.
  503. */
  504. function number(rule, value, callback, source, options) {
  505. var errors = [];
  506. var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
  507. if (validate) {
  508. if (value === '') {
  509. value = undefined;
  510. }
  511. if (isEmptyValue(value) && !rule.required) {
  512. return callback();
  513. }
  514. rules.required(rule, value, source, errors, options);
  515. if (value !== undefined) {
  516. rules.type(rule, value, source, errors, options);
  517. rules.range(rule, value, source, errors, options);
  518. }
  519. }
  520. callback(errors);
  521. }
  522. /**
  523. * Validates a boolean.
  524. *
  525. * @param rule The validation rule.
  526. * @param value The value of the field on the source object.
  527. * @param callback The callback function.
  528. * @param source The source object being validated.
  529. * @param options The validation options.
  530. * @param options.messages The validation messages.
  531. */
  532. function _boolean(rule, value, callback, source, options) {
  533. var errors = [];
  534. var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
  535. if (validate) {
  536. if (isEmptyValue(value) && !rule.required) {
  537. return callback();
  538. }
  539. rules.required(rule, value, source, errors, options);
  540. if (value !== undefined) {
  541. rules.type(rule, value, source, errors, options);
  542. }
  543. }
  544. callback(errors);
  545. }
  546. /**
  547. * Validates the regular expression type.
  548. *
  549. * @param rule The validation rule.
  550. * @param value The value of the field on the source object.
  551. * @param callback The callback function.
  552. * @param source The source object being validated.
  553. * @param options The validation options.
  554. * @param options.messages The validation messages.
  555. */
  556. function regexp(rule, value, callback, source, options) {
  557. var errors = [];
  558. var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
  559. if (validate) {
  560. if (isEmptyValue(value) && !rule.required) {
  561. return callback();
  562. }
  563. rules.required(rule, value, source, errors, options);
  564. if (!isEmptyValue(value)) {
  565. rules.type(rule, value, source, errors, options);
  566. }
  567. }
  568. callback(errors);
  569. }
  570. /**
  571. * Validates a number is an integer.
  572. *
  573. * @param rule The validation rule.
  574. * @param value The value of the field on the source object.
  575. * @param callback The callback function.
  576. * @param source The source object being validated.
  577. * @param options The validation options.
  578. * @param options.messages The validation messages.
  579. */
  580. function integer(rule, value, callback, source, options) {
  581. var errors = [];
  582. var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
  583. if (validate) {
  584. if (isEmptyValue(value) && !rule.required) {
  585. return callback();
  586. }
  587. rules.required(rule, value, source, errors, options);
  588. if (value !== undefined) {
  589. rules.type(rule, value, source, errors, options);
  590. rules.range(rule, value, source, errors, options);
  591. }
  592. }
  593. callback(errors);
  594. }
  595. /**
  596. * Validates a number is a floating point number.
  597. *
  598. * @param rule The validation rule.
  599. * @param value The value of the field on the source object.
  600. * @param callback The callback function.
  601. * @param source The source object being validated.
  602. * @param options The validation options.
  603. * @param options.messages The validation messages.
  604. */
  605. function floatFn(rule, value, callback, source, options) {
  606. var errors = [];
  607. var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
  608. if (validate) {
  609. if (isEmptyValue(value) && !rule.required) {
  610. return callback();
  611. }
  612. rules.required(rule, value, source, errors, options);
  613. if (value !== undefined) {
  614. rules.type(rule, value, source, errors, options);
  615. rules.range(rule, value, source, errors, options);
  616. }
  617. }
  618. callback(errors);
  619. }
  620. /**
  621. * Validates an array.
  622. *
  623. * @param rule The validation rule.
  624. * @param value The value of the field on the source object.
  625. * @param callback The callback function.
  626. * @param source The source object being validated.
  627. * @param options The validation options.
  628. * @param options.messages The validation messages.
  629. */
  630. function array(rule, value, callback, source, options) {
  631. var errors = [];
  632. var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
  633. if (validate) {
  634. if (isEmptyValue(value, 'array') && !rule.required) {
  635. return callback();
  636. }
  637. rules.required(rule, value, source, errors, options, 'array');
  638. if (!isEmptyValue(value, 'array')) {
  639. rules.type(rule, value, source, errors, options);
  640. rules.range(rule, value, source, errors, options);
  641. }
  642. }
  643. callback(errors);
  644. }
  645. /**
  646. * Validates an object.
  647. *
  648. * @param rule The validation rule.
  649. * @param value The value of the field on the source object.
  650. * @param callback The callback function.
  651. * @param source The source object being validated.
  652. * @param options The validation options.
  653. * @param options.messages The validation messages.
  654. */
  655. function object(rule, value, callback, source, options) {
  656. var errors = [];
  657. var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
  658. if (validate) {
  659. if (isEmptyValue(value) && !rule.required) {
  660. return callback();
  661. }
  662. rules.required(rule, value, source, errors, options);
  663. if (value !== undefined) {
  664. rules.type(rule, value, source, errors, options);
  665. }
  666. }
  667. callback(errors);
  668. }
  669. var ENUM$1 = 'enum';
  670. /**
  671. * Validates an enumerable list.
  672. *
  673. * @param rule The validation rule.
  674. * @param value The value of the field on the source object.
  675. * @param callback The callback function.
  676. * @param source The source object being validated.
  677. * @param options The validation options.
  678. * @param options.messages The validation messages.
  679. */
  680. function enumerable$1(rule, value, callback, source, options) {
  681. var errors = [];
  682. var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
  683. if (validate) {
  684. if (isEmptyValue(value) && !rule.required) {
  685. return callback();
  686. }
  687. rules.required(rule, value, source, errors, options);
  688. if (value !== undefined) {
  689. rules[ENUM$1](rule, value, source, errors, options);
  690. }
  691. }
  692. callback(errors);
  693. }
  694. /**
  695. * Validates a regular expression pattern.
  696. *
  697. * Performs validation when a rule only contains
  698. * a pattern property but is not declared as a string type.
  699. *
  700. * @param rule The validation rule.
  701. * @param value The value of the field on the source object.
  702. * @param callback The callback function.
  703. * @param source The source object being validated.
  704. * @param options The validation options.
  705. * @param options.messages The validation messages.
  706. */
  707. function pattern$2(rule, value, callback, source, options) {
  708. var errors = [];
  709. var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
  710. if (validate) {
  711. if (isEmptyValue(value, 'string') && !rule.required) {
  712. return callback();
  713. }
  714. rules.required(rule, value, source, errors, options);
  715. if (!isEmptyValue(value, 'string')) {
  716. rules.pattern(rule, value, source, errors, options);
  717. }
  718. }
  719. callback(errors);
  720. }
  721. function date(rule, value, callback, source, options) {
  722. var errors = [];
  723. var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
  724. if (validate) {
  725. if (isEmptyValue(value) && !rule.required) {
  726. return callback();
  727. }
  728. rules.required(rule, value, source, errors, options);
  729. if (!isEmptyValue(value)) {
  730. var dateObject;
  731. if (typeof value === 'number') {
  732. dateObject = new Date(value);
  733. } else {
  734. dateObject = value;
  735. }
  736. rules.type(rule, dateObject, source, errors, options);
  737. if (dateObject) {
  738. rules.range(rule, dateObject.getTime(), source, errors, options);
  739. }
  740. }
  741. }
  742. callback(errors);
  743. }
  744. function required$1(rule, value, callback, source, options) {
  745. var errors = [];
  746. var type = Array.isArray(value) ? 'array' : typeof value;
  747. rules.required(rule, value, source, errors, options, type);
  748. callback(errors);
  749. }
  750. function type$1(rule, value, callback, source, options) {
  751. var ruleType = rule.type;
  752. var errors = [];
  753. var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
  754. if (validate) {
  755. if (isEmptyValue(value, ruleType) && !rule.required) {
  756. return callback();
  757. }
  758. rules.required(rule, value, source, errors, options, ruleType);
  759. if (!isEmptyValue(value, ruleType)) {
  760. rules.type(rule, value, source, errors, options);
  761. }
  762. }
  763. callback(errors);
  764. }
  765. /**
  766. * Performs validation for any type.
  767. *
  768. * @param rule The validation rule.
  769. * @param value The value of the field on the source object.
  770. * @param callback The callback function.
  771. * @param source The source object being validated.
  772. * @param options The validation options.
  773. * @param options.messages The validation messages.
  774. */
  775. function any(rule, value, callback, source, options) {
  776. var errors = [];
  777. var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
  778. if (validate) {
  779. if (isEmptyValue(value) && !rule.required) {
  780. return callback();
  781. }
  782. rules.required(rule, value, source, errors, options);
  783. }
  784. callback(errors);
  785. }
  786. var validators = {
  787. string: string,
  788. method: method,
  789. number: number,
  790. "boolean": _boolean,
  791. regexp: regexp,
  792. integer: integer,
  793. "float": floatFn,
  794. array: array,
  795. object: object,
  796. "enum": enumerable$1,
  797. pattern: pattern$2,
  798. date: date,
  799. url: type$1,
  800. hex: type$1,
  801. email: type$1,
  802. required: required$1,
  803. any: any
  804. };
  805. function newMessages() {
  806. return {
  807. "default": 'Validation error on field %s',
  808. required: '%s is required',
  809. "enum": '%s must be one of %s',
  810. whitespace: '%s cannot be empty',
  811. date: {
  812. format: '%s date %s is invalid for format %s',
  813. parse: '%s date could not be parsed, %s is invalid ',
  814. invalid: '%s date %s is invalid'
  815. },
  816. types: {
  817. string: '%s is not a %s',
  818. method: '%s is not a %s (function)',
  819. array: '%s is not an %s',
  820. object: '%s is not an %s',
  821. number: '%s is not a %s',
  822. date: '%s is not a %s',
  823. "boolean": '%s is not a %s',
  824. integer: '%s is not an %s',
  825. "float": '%s is not a %s',
  826. regexp: '%s is not a valid %s',
  827. email: '%s is not a valid %s',
  828. url: '%s is not a valid %s',
  829. hex: '%s is not a valid %s'
  830. },
  831. string: {
  832. len: '%s must be exactly %s characters',
  833. min: '%s must be at least %s characters',
  834. max: '%s cannot be longer than %s characters',
  835. range: '%s must be between %s and %s characters'
  836. },
  837. number: {
  838. len: '%s must equal %s',
  839. min: '%s cannot be less than %s',
  840. max: '%s cannot be greater than %s',
  841. range: '%s must be between %s and %s'
  842. },
  843. array: {
  844. len: '%s must be exactly %s in length',
  845. min: '%s cannot be less than %s in length',
  846. max: '%s cannot be greater than %s in length',
  847. range: '%s must be between %s and %s in length'
  848. },
  849. pattern: {
  850. mismatch: '%s value %s does not match pattern %s'
  851. },
  852. clone: function clone() {
  853. var cloned = JSON.parse(JSON.stringify(this));
  854. cloned.clone = this.clone;
  855. return cloned;
  856. }
  857. };
  858. }
  859. var messages = newMessages();
  860. /**
  861. * Encapsulates a validation schema.
  862. *
  863. * @param descriptor An object declaring validation rules
  864. * for this schema.
  865. */
  866. function Schema(descriptor) {
  867. this.rules = null;
  868. this._messages = messages;
  869. this.define(descriptor);
  870. }
  871. Schema.prototype = {
  872. messages: function messages(_messages) {
  873. if (_messages) {
  874. this._messages = deepMerge(newMessages(), _messages);
  875. }
  876. return this._messages;
  877. },
  878. define: function define(rules) {
  879. if (!rules) {
  880. throw new Error('Cannot configure a schema with no rules');
  881. }
  882. if (typeof rules !== 'object' || Array.isArray(rules)) {
  883. throw new Error('Rules must be an object');
  884. }
  885. this.rules = {};
  886. var z;
  887. var item;
  888. for (z in rules) {
  889. if (rules.hasOwnProperty(z)) {
  890. item = rules[z];
  891. this.rules[z] = Array.isArray(item) ? item : [item];
  892. }
  893. }
  894. },
  895. validate: function validate(source_, o, oc) {
  896. var _this = this;
  897. if (o === void 0) {
  898. o = {};
  899. }
  900. if (oc === void 0) {
  901. oc = function oc() {
  902. };
  903. }
  904. var source = source_;
  905. var options = o;
  906. var callback = oc;
  907. if (typeof options === 'function') {
  908. callback = options;
  909. options = {};
  910. }
  911. if (!this.rules || Object.keys(this.rules).length === 0) {
  912. if (callback) {
  913. callback();
  914. }
  915. return Promise.resolve();
  916. }
  917. function complete(results) {
  918. var i;
  919. var errors = [];
  920. var fields = {};
  921. function add(e) {
  922. if (Array.isArray(e)) {
  923. var _errors;
  924. errors = (_errors = errors).concat.apply(_errors, e);
  925. } else {
  926. errors.push(e);
  927. }
  928. }
  929. for (i = 0; i < results.length; i++) {
  930. add(results[i]);
  931. }
  932. if (!errors.length) {
  933. errors = null;
  934. fields = null;
  935. } else {
  936. fields = convertFieldsError(errors);
  937. }
  938. callback(errors, fields);
  939. }
  940. if (options.messages) {
  941. var messages$1 = this.messages();
  942. if (messages$1 === messages) {
  943. messages$1 = newMessages();
  944. }
  945. deepMerge(messages$1, options.messages);
  946. options.messages = messages$1;
  947. } else {
  948. options.messages = this.messages();
  949. }
  950. var arr;
  951. var value;
  952. var series = {};
  953. var keys = options.keys || Object.keys(this.rules);
  954. keys.forEach(function (z) {
  955. arr = _this.rules[z];
  956. value = source[z];
  957. arr.forEach(function (r) {
  958. var rule = r;
  959. if (typeof rule.transform === 'function') {
  960. if (source === source_) {
  961. source = _extends({}, source);
  962. }
  963. value = source[z] = rule.transform(value);
  964. }
  965. if (typeof rule === 'function') {
  966. rule = {
  967. validator: rule
  968. };
  969. } else {
  970. rule = _extends({}, rule);
  971. }
  972. rule.validator = _this.getValidationMethod(rule);
  973. rule.field = z;
  974. rule.fullField = rule.fullField || z;
  975. rule.type = _this.getType(rule);
  976. if (!rule.validator) {
  977. return;
  978. }
  979. series[z] = series[z] || [];
  980. series[z].push({
  981. rule: rule,
  982. value: value,
  983. source: source,
  984. field: z
  985. });
  986. });
  987. });
  988. var errorFields = {};
  989. return asyncMap(series, options, function (data, doIt) {
  990. var rule = data.rule;
  991. var deep = (rule.type === 'object' || rule.type === 'array') && (typeof rule.fields === 'object' || typeof rule.defaultField ===
  992. 'object');
  993. deep = deep && (rule.required || !rule.required && data.value);
  994. rule.field = data.field;
  995. function addFullfield(key, schema) {
  996. return _extends({}, schema, {
  997. fullField: rule.fullField + "." + key
  998. });
  999. }
  1000. function cb(e) {
  1001. if (e === void 0) {
  1002. e = [];
  1003. }
  1004. var errors = e;
  1005. if (!Array.isArray(errors)) {
  1006. errors = [errors];
  1007. }
  1008. if (!options.suppressWarning && errors.length) {
  1009. Schema.warning('async-validator:', errors);
  1010. }
  1011. if (errors.length && rule.message) {
  1012. errors = [].concat(rule.message);
  1013. }
  1014. errors = errors.map(complementError(rule));
  1015. if (options.first && errors.length) {
  1016. errorFields[rule.field] = 1;
  1017. return doIt(errors);
  1018. }
  1019. if (!deep) {
  1020. doIt(errors);
  1021. } else {
  1022. // if rule is required but the target object
  1023. // does not exist fail at the rule level and don't
  1024. // go deeper
  1025. if (rule.required && !data.value) {
  1026. if (rule.message) {
  1027. errors = [].concat(rule.message).map(complementError(rule));
  1028. } else if (options.error) {
  1029. errors = [options.error(rule, format(options.messages.required, rule.field))];
  1030. } else {
  1031. errors = [];
  1032. }
  1033. return doIt(errors);
  1034. }
  1035. var fieldsSchema = {};
  1036. if (rule.defaultField) {
  1037. for (var k in data.value) {
  1038. if (data.value.hasOwnProperty(k)) {
  1039. fieldsSchema[k] = rule.defaultField;
  1040. }
  1041. }
  1042. }
  1043. fieldsSchema = _extends({}, fieldsSchema, {}, data.rule.fields);
  1044. for (var f in fieldsSchema) {
  1045. if (fieldsSchema.hasOwnProperty(f)) {
  1046. var fieldSchema = Array.isArray(fieldsSchema[f]) ? fieldsSchema[f] : [fieldsSchema[f]];
  1047. fieldsSchema[f] = fieldSchema.map(addFullfield.bind(null, f));
  1048. }
  1049. }
  1050. var schema = new Schema(fieldsSchema);
  1051. schema.messages(options.messages);
  1052. if (data.rule.options) {
  1053. data.rule.options.messages = options.messages;
  1054. data.rule.options.error = options.error;
  1055. }
  1056. schema.validate(data.value, data.rule.options || options, function (errs) {
  1057. var finalErrors = [];
  1058. if (errors && errors.length) {
  1059. finalErrors.push.apply(finalErrors, errors);
  1060. }
  1061. if (errs && errs.length) {
  1062. finalErrors.push.apply(finalErrors, errs);
  1063. }
  1064. doIt(finalErrors.length ? finalErrors : null);
  1065. });
  1066. }
  1067. }
  1068. var res;
  1069. if (rule.asyncValidator) {
  1070. res = rule.asyncValidator(rule, data.value, cb, data.source, options);
  1071. } else if (rule.validator) {
  1072. res = rule.validator(rule, data.value, cb, data.source, options);
  1073. if (res === true) {
  1074. cb();
  1075. } else if (res === false) {
  1076. cb(rule.message || rule.field + " fails");
  1077. } else if (res instanceof Array) {
  1078. cb(res);
  1079. } else if (res instanceof Error) {
  1080. cb(res.message);
  1081. }
  1082. }
  1083. if (res && res.then) {
  1084. res.then(function () {
  1085. return cb();
  1086. }, function (e) {
  1087. return cb(e);
  1088. });
  1089. }
  1090. }, function (results) {
  1091. complete(results);
  1092. });
  1093. },
  1094. getType: function getType(rule) {
  1095. if (rule.type === undefined && rule.pattern instanceof RegExp) {
  1096. rule.type = 'pattern';
  1097. }
  1098. if (typeof rule.validator !== 'function' && rule.type && !validators.hasOwnProperty(rule.type)) {
  1099. throw new Error(format('Unknown rule type %s', rule.type));
  1100. }
  1101. return rule.type || 'string';
  1102. },
  1103. getValidationMethod: function getValidationMethod(rule) {
  1104. if (typeof rule.validator === 'function') {
  1105. return rule.validator;
  1106. }
  1107. var keys = Object.keys(rule);
  1108. var messageIndex = keys.indexOf('message');
  1109. if (messageIndex !== -1) {
  1110. keys.splice(messageIndex, 1);
  1111. }
  1112. if (keys.length === 1 && keys[0] === 'required') {
  1113. return validators.required;
  1114. }
  1115. return validators[this.getType(rule)] || false;
  1116. }
  1117. };
  1118. Schema.register = function register(type, validator) {
  1119. if (typeof validator !== 'function') {
  1120. throw new Error('Cannot register a validator by type, validator is not a function');
  1121. }
  1122. validators[type] = validator;
  1123. };
  1124. Schema.warning = warning;
  1125. Schema.messages = messages;
  1126. export default Schema;
  1127. //# sourceMappingURL=index.js.map