async-validator.js 33 KB

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