validator.js 7.91 KB
/** 表单校验 — @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
	}
}