validator.js 7.99 KB
/** 表单校验 — @see packageDynamicForm/docs/ARCHITECTURE.md */
import {
	getVisibleList,
	getVisibleLeafFields,
	getVisibleGroupChildFields,
	resolveEffectiveRowFields
} from './visibility.js'
import { buildGroupErrorKey, getGroupRows } from './group-values.js'
import { isCarBrandComplete, resolveCarBrandValueForValidation } from './car-brand-value.js'
import {
	resolveNumberInputMaxLength,
	isNonNegativeIntegerInput,
	isNumberInputDecimalMode
} from './field-input-limits.js'
import { coerceSelectValue } from './select-value.js'
import {
	getFieldTypeStrategy,
	validateFieldByTypeStrategy,
	resolveSubformChildValidationValue
} from './field-types/registry.js'
import { parseDateTimeLocal, resolveNotAfterNow } from './datetime-picker-mode.js'
import {
	isVinScanField,
	validatePhoneFormat,
	validateVinSyncFormat,
	resolveVinInputMaxLength,
	shouldCheckVinApi,
	VIN_API_FAIL_MSG
} from './field-format-rules.js'
import { resolveSubformMaxRows } from './subform-limits.js'

function isEmptyValue(value) {
	if (value === undefined || value === null) {
		return true
	}
	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 hasMeaningfulRowValue(value) {
	return value !== undefined && value !== null && value !== ''
}

/** subform 单元格校验取值(App 双 key / carBrand 优先 meta) */
function resolveSubformChildValue(child, row, rowField) {
	if (child?.type === 'carBrandSelect') {
		return resolveCarBrandValueForValidation(rowField, child.key, row?.[child.key])
	}
	if (getFieldTypeStrategy(child?.type)?.resolveValidationValue) {
		return resolveSubformChildValidationValue(child, rowField, row?.[child.key])
	}
	if (rowField && hasMeaningfulRowValue(rowField.value)) {
		return rowField.value
	}
	return row?.[child.key]
}

function appendVinApiError(field, value, errors, vinApiValidMap, errorKey) {
	if (!isVinScanField(field) || !shouldCheckVinApi(value)) {
		return
	}
	if (!vinApiValidMap) {
		return
	}
	if (vinApiValidMap[errorKey] !== true) {
		errors.push(VIN_API_FAIL_MSG)
	}
}

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)
		}
	}

	if (fieldType === 'input' && isVinScanField(field)) {
		const vinMsg = validateVinSyncFormat(
			value,
			resolveVinInputMaxLength(field)
		)
		if (vinMsg) {
			errors.push(vinMsg)
		}
	}

	const dateOnly = field.type === 'date' || rules.format === 'date'

	if (fieldType === 'datetime' && !dateOnly && resolveNotAfterNow(field)) {
		const picked = parseDateTimeLocal(value)
		const now = new Date()
		if (picked && picked.getTime() > now.getTime()) {
			errors.push(`${field.label}不能晚于当前时间`)
		}
	} else if (
		(field.type === 'date' || fieldType === 'datetime') &&
		rules.maxDate === 'today' &&
		(dateOnly || !resolveNotAfterNow(field))
	) {
		const picked = parseFieldDate(value)
		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}不能为空`)
	}

	appendVinApiError(field, value, errors, options.vinApiValidMap, options.errorKey)

	return errors
}

/** 校验可见固定字段与 subform 行内字段
 *  @returns {{ ok: boolean, errors: Array, errorMap: object }} */
export function validateForm(list = [], ctx, values, groupRowsCache = {}, options = {}) {
	const errors = []
	const errorMap = {}
	const visibleList = getVisibleList(list, ctx, values)

	getVisibleLeafFields(list, ctx, values).forEach(field => {
		const fieldErrors = validateField(field, values[field.key], {
			vinApiValidMap: options.vinApiValidMap,
			errorKey: field.key
		})
		if (fieldErrors.length) {
			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, {
						vinApiValidMap: options.vinApiValidMap,
						errorKey
					})
					if (fieldErrors.length) {
						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
	}
}