async-validator.js 38 KB

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