index.js 37 KB

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