validator.js
7.91 KB
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
/** 表单校验 — @see packageDynamicForm/docs/ARCHITECTURE.md */
import {
getVisibleList,
getVisibleLeafFields,
getVisibleGroupChildFields,
resolveEffectiveRowFields
} from './visibility.js'
import { buildGroupErrorKey, getGroupRows } from './group-values.js'
import { isCarBrandComplete } from './car-brand-value.js'
import {
resolveNumberInputMaxLength,
isNonNegativeIntegerInput,
isNumberInputDecimalMode
} from './field-input-limits.js'
import { coerceSelectValue } from './select-value.js'
import {
validateFieldByTypeStrategy
} from './field-types/registry.js'
import { parseDateTimeLocal, resolveNotAfterNow } from './datetime-picker-mode.js'
import {
hasPlanImportDateMarker,
unwrapPlanImportDate
} from './plan-import-date-value.js'
import {
validatePhoneFormat
} from './field-format-rules.js'
import { resolveSubformMaxRows } from './subform-limits.js'
import { resolveSubformChildValue } from './subform-child-validation-value.js'
import { validateSubformDuplicates } from './subform-duplicate-validation.js'
import { validateConfiguredFieldComparisons } from './field-comparison.js'
function isEmptyValue(value) {
if (value === undefined || value === null) {
return true
}
if (hasPlanImportDateMarker(value)) {
const scalar = unwrapPlanImportDate(value)
return scalar === '' || scalar.trim() === ''
}
if (Array.isArray(value) && value.length === 0) {
return true
}
if (typeof value === 'string' && value.trim() === '') {
return true
}
return false
}
function parseFieldDate(value) {
if (!value) return null
const date = new Date(value)
return Number.isNaN(date.getTime()) ? null : date
}
function validateField(field, value, options = {}) {
const fieldType = field.type === 'date' ? 'datetime' : field.type
if (fieldType === 'divider' || field.disabled) {
return []
}
if (fieldType === 'select') {
value = coerceSelectValue(value)
}
const rules = field.rules || {}
const errors = []
const registryErrors = validateFieldByTypeStrategy(field, value, options)
if (registryErrors?.length) {
return registryErrors
}
if (fieldType === 'carBrandSelect') {
if (field.required && !isCarBrandComplete(value)) {
errors.push(`${field.label}不能为空`)
return errors
}
return errors
}
if (field.required && isEmptyValue(value)) {
errors.push(`${field.label}不能为空`)
return errors
}
if (isEmptyValue(value)) {
return errors
}
if (fieldType === 'numberInput') {
const num = Number(value)
if (Number.isNaN(num)) {
errors.push(`${field.label}必须为数字`)
return errors
}
if (isNumberInputDecimalMode(field)) {
const min = rules.min ?? 0
if (num < min) {
errors.push(`${field.label}不能小于${min}`)
}
if (!/^\d+(\.\d{1,2})?$/.test(String(value))) {
errors.push(`${field.label}最多两位小数`)
}
} else if (isNonNegativeIntegerInput(field)) {
const min = rules.min ?? 0
if (num < min) {
errors.push(`${field.label}不能小于${min}`)
}
if (!Number.isInteger(num)) {
errors.push(`${field.label}必须为整数`)
}
} else {
if (rules.min !== undefined && num < rules.min) {
errors.push(`${field.label}不能小于${rules.min}`)
}
if (rules.integer && !Number.isInteger(num)) {
errors.push(`${field.label}必须为整数`)
}
}
const maxLength = resolveNumberInputMaxLength(field)
if (maxLength != null && String(value).length > maxLength) {
errors.push(`${field.label}不能超过${maxLength}位`)
}
}
if ((fieldType === 'input' || fieldType === 'textarea') && rules.maxLength !== undefined) {
if (String(value).length > rules.maxLength) {
errors.push(`${field.label}不能超过${rules.maxLength}字`)
}
}
if (fieldType === 'phoneInput') {
const phoneMsg = validatePhoneFormat(value)
if (phoneMsg) {
errors.push(phoneMsg)
}
}
const dateOnly = field.type === 'date' || rules.format === 'date'
const skipMaxDate = hasPlanImportDateMarker(value)
const dateValue = skipMaxDate ? unwrapPlanImportDate(value) : value
if (fieldType === 'datetime' && !dateOnly && resolveNotAfterNow(field) && !skipMaxDate) {
const picked = parseDateTimeLocal(dateValue)
const now = new Date()
if (picked && picked.getTime() > now.getTime()) {
errors.push(`${field.label}不能晚于当前时间`)
}
} else if (
!skipMaxDate &&
(field.type === 'date' || fieldType === 'datetime') &&
rules.maxDate === 'today' &&
(dateOnly || !resolveNotAfterNow(field))
) {
const picked = parseFieldDate(dateValue)
const today = new Date()
today.setHours(23, 59, 59, 999)
if (picked && picked.getTime() > today.getTime()) {
errors.push(`${field.label}不能晚于今天`)
}
}
if (fieldType === 'multipleSelect' && field.required && isEmptyValue(value)) {
errors.push(`${field.label}不能为空`)
}
if (!errors.length) {
errors.push(...validateConfiguredFieldComparisons(field, value, options.values || {}))
}
return errors
}
/**
* 按模板声明校验可见固定字段、subform 行内字段及重复值规则。
* @param {Array<Object>} list 模板字段列表
* @param {Object} ctx 页面上下文
* @param {Object} values 当前表单值
* @param {Object<string, Array<Object>>} groupRowsCache subform 行字段缓存
* @param {Object} options 字段类型策略的通用校验参数
* @returns {{ ok: boolean, errors: Array<Object>, errorMap: Object<string, string> }}
*/
export function validateForm(list = [], ctx, values, groupRowsCache = {}, options = {}) {
const duplicateValidation = validateSubformDuplicates(
list,
ctx,
values,
groupRowsCache
)
const errors = [...duplicateValidation.errors]
const errorMap = { ...duplicateValidation.errorMap }
const visibleList = getVisibleList(list, ctx, values)
getVisibleLeafFields(list, ctx, values).forEach(field => {
const fieldErrors = validateField(field, values[field.key], { ...options, values })
if (fieldErrors.length) {
if (!(field.key in errorMap)) {
errorMap[field.key] = fieldErrors[0]
}
errors.push({
key: field.key,
label: field.label,
message: fieldErrors[0]
})
}
})
visibleList
.filter(field => field.type === 'subform')
.forEach(group => {
const rows = getGroupRows(values, group.key)
const rowFieldsList = groupRowsCache[group.key] || []
if (!rows.length && !rowFieldsList.length) {
return
}
const minRows = group.rules?.minRows ?? 0
const maxRows = resolveSubformMaxRows(group)
const rowCount = Math.max(rows.length, rowFieldsList.length)
if (minRows > 0 && rowCount < minRows) {
const message = `${group.label}至少填写${minRows}条`
errorMap[group.key] = message
errors.push({ key: group.key, label: group.label, message })
return
}
if (rowCount > maxRows) {
const message = `${group.label}最多${maxRows}条`
errorMap[group.key] = message
errors.push({ key: group.key, label: group.label, message })
}
for (let rowIndex = 0; rowIndex < rowCount; rowIndex++) {
const row = rows[rowIndex] || {}
const rowFields = rowFieldsList[rowIndex] || []
const effectiveRowFields = resolveEffectiveRowFields(group, rowFields, row)
const children = getVisibleGroupChildFields(
group,
ctx,
values,
list,
effectiveRowFields,
row
)
children.forEach(child => {
const rowField = effectiveRowFields.find(f => f.key === child.key)
const fieldValue = resolveSubformChildValue(child, row, rowField)
const errorKey = buildGroupErrorKey(group.key, rowIndex, child.key)
const fieldErrors = validateField(child, fieldValue, {
...options,
values: { ...values, ...row },
errorKey
})
if (fieldErrors.length) {
if (!(errorKey in errorMap)) {
errorMap[errorKey] = fieldErrors[0]
}
errors.push({
key: errorKey,
label: `${group.label} 第${rowIndex + 1}行 ${child.label}`,
message: fieldErrors[0],
groupKey: group.key,
rowIndex
})
}
})
}
})
return {
ok: errors.length === 0,
errors,
errorMap
}
}