This repository was archived by the owner on Sep 19, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathaccordion.js
70 lines (57 loc) · 1.9 KB
/
accordion.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/* eslint-disable import/no-cycle */
import { validate } from 'validate.js'
import { validateModel } from 'models/validate'
import {
MISSING_ITEMS, INVALID_BRANCH, INVALID_VALIDATOR, INVALID_ITEM,
} from 'constants/errors'
import { NO } from 'constants/values'
/**
* Accordion:
* {
* items: [
* {
* Item: {},
* }
* ],
* branch: { value: 'No' },
* }
*/
const accordionValidator = (value, options, key, attributes, globalOptions) => {
if (validate.isEmpty(value)) return null // Don't validate if there is no value
const {
validator, length, ignoreBranch, itemsValidator,
} = options
if (!validator) return INVALID_VALIDATOR
let errors = []
const { items, branch } = value
// Validate branch
if (!ignoreBranch && (!branch || !branch.value || branch.value !== NO)) {
errors.push(INVALID_BRANCH)
}
if (!items || (items && items.length < 1)) {
errors.push(MISSING_ITEMS)
} else {
// Validate item length
if (length) {
const lengthErrors = validateModel({ items }, { items: { length } }, { ...globalOptions })
if (lengthErrors !== true) errors = [...errors, ...lengthErrors]
}
let itemsErrors = []
for (let i = 0; i < items.length; i += 1) {
const { Item, uuid } = items[i]
const itemId = uuid || i
if (!Item) itemsErrors = itemsErrors.concat(`${itemId}.${INVALID_ITEM}`)
const itemErrors = validateModel(Item, validator, { ...globalOptions, ...options })
if (itemErrors !== true) itemsErrors = itemsErrors.concat(itemErrors.map(e => `${itemId}.${e}`))
}
if (itemsErrors.length) errors = [...errors, ...itemsErrors]
// Optional function to test against all of the items
if (itemsValidator) {
const itemsValidatorErrors = itemsValidator(items)
if (itemsValidatorErrors) errors.push(itemsValidatorErrors)
}
}
if (errors.length) return errors
return null
}
export default accordionValidator