index.js 38 KB

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