validator.js 5.08 KB
/** 表单校验 — @see docs/features/packageDynamicForm/ARCHITECTURE.md */
import { getVisibleList, getVisibleLeafFields, getVisibleGroupChildFields } from './visibility.js'
import { buildGroupErrorKey, getGroupRows } from './group-values.js'
import { isCarBrandComplete } from './car-brand-value.js'
import { resolveNumberInputMaxLength } from './field-input-limits.js'
import { coerceSelectValue } from './select-value.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
}

const PHONE_PATTERN = /^1\d{10}$/

function parseFieldDate(value) {
	if (!value) return null
	const date = new Date(value)
	return Number.isNaN(date.getTime()) ? null : date
}

function validateField(field, value) {
	if (field.type === 'divider' || field.disabled) {
		return []
	}

	if (field.type === 'select') {
		value = coerceSelectValue(value)
	}

	const rules = field.rules || {}
	const errors = []

	if (field.type === '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 (field.type === 'numberInput') {
		const num = Number(value)
		if (Number.isNaN(num)) {
			errors.push(`${field.label}必须为数字`)
			return errors
		}
		if (rules.min !== undefined && num < rules.min) {
			errors.push(`${field.label}不能小于${rules.min}`)
		}
		if (rules.integer && !Number.isInteger(num)) {
			errors.push(`${field.label}必须为整数`)
		}
		if (rules.decimal && !/^\d+(\.\d{1,2})?$/.test(String(value))) {
			errors.push(`${field.label}最多两位小数`)
		}
		const maxLength = resolveNumberInputMaxLength(field)
		if (maxLength != null && String(value).length > maxLength) {
			errors.push(`${field.label}不能超过${maxLength}位`)
		}
	}

	if ((field.type === 'input' || field.type === 'textarea') && rules.maxLength !== undefined) {
		if (String(value).length > rules.maxLength) {
			errors.push(`${field.label}不能超过${rules.maxLength}字`)
		}
	}

	if (field.type === 'phoneInput') {
		if (!PHONE_PATTERN.test(String(value))) {
			errors.push(`${field.label}格式不正确`)
		}
	}

	if (field.type === 'datetime' && rules.maxDate === 'today') {
		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 ((field.type === 'select' || field.type === 'radio') && field.required && isEmptyValue(value)) {
		errors.push(`${field.label}不能为空`)
	}

	if (field.type === 'multipleSelect' && field.required && isEmptyValue(value)) {
		errors.push(`${field.label}不能为空`)
	}

	return errors
}

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

	getVisibleLeafFields(list, ctx, values).forEach(field => {
		const fieldErrors = validateField(field, values[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)
			if (!rows.length) {
				return
			}

			const minRows = group.rules?.minRows ?? 0
			const maxRows = group.rules?.maxRows ?? 20

			if (minRows > 0 && rows.length < minRows) {
				const message = `${group.label}至少填写${minRows}条`
				errorMap[group.key] = message
				errors.push({ key: group.key, label: group.label, message })
				return
			}
			if (rows.length > maxRows) {
				const message = `${group.label}最多${maxRows}条`
				errorMap[group.key] = message
				errors.push({ key: group.key, label: group.label, message })
			}

			const rowFieldsList = groupRowsCache[group.key] || []
			rows.forEach((row, rowIndex) => {
				const rowFields = rowFieldsList[rowIndex] || []
				const children = getVisibleGroupChildFields(group, ctx, values, list, rowFields)
				children.forEach(child => {
					const rowField = rowFields.find(f => f.key === child.key)
					const fieldValue = rowField?.value !== undefined ? rowField.value : row[child.key]
					const fieldErrors = validateField(child, fieldValue)
					if (fieldErrors.length) {
						const errorKey = buildGroupErrorKey(group.key, rowIndex, child.key)
						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
	}
}