field-comparison.js 3.01 KB
/**
 * @file 配置型跨字段数值比较。
 * 仅消费 schema.rules.comparisons,不参与字段显隐或页面状态。
 */

function normalizeDecimal(value) {
	if (value === undefined || value === null) return null
	const match = /^([+-]?)(\d+)(?:\.(\d+))?$/.exec(String(value).trim())
	if (!match) return null
	const integer = match[2].replace(/^0+(?=\d)/, '')
	const fraction = (match[3] || '').replace(/0+$/, '')
	const isZero = integer === '0' && fraction === ''
	return {
		negative: !isZero && match[1] === '-',
		integer,
		fraction
	}
}

function compareMagnitude(left, right) {
	if (left.integer.length !== right.integer.length) {
		return left.integer.length > right.integer.length ? 1 : -1
	}
	if (left.integer !== right.integer) {
		return left.integer > right.integer ? 1 : -1
	}
	const length = Math.max(left.fraction.length, right.fraction.length)
	const leftFraction = left.fraction.padEnd(length, '0')
	const rightFraction = right.fraction.padEnd(length, '0')
	if (leftFraction === rightFraction) return 0
	return leftFraction > rightFraction ? 1 : -1
}

/**
 * 精确比较十进制文本,避免跨字段数量比较经过原生浮点转换。
 * @param {string|number} left 左值
 * @param {string|number} right 右值
 * @returns {-1|0|1|null} 左小于/等于/大于右值,非法输入返回 null
 */
export function compareExactDecimals(left, right) {
	const normalizedLeft = normalizeDecimal(left)
	const normalizedRight = normalizeDecimal(right)
	if (!normalizedLeft || !normalizedRight) return null
	if (normalizedLeft.negative !== normalizedRight.negative) {
		return normalizedLeft.negative ? -1 : 1
	}
	const magnitude = compareMagnitude(normalizedLeft, normalizedRight)
	if (magnitude === 0) return 0
	return normalizedLeft.negative ? -magnitude : magnitude
}

function isComparisonSatisfied(operator, compared) {
	if (operator === 'lt') return compared < 0
	if (operator === 'lte') return compared <= 0
	if (operator === 'gt') return compared > 0
	if (operator === 'gte') return compared >= 0
	if (operator === 'eq') return compared === 0
	return true
}

/**
 * 执行字段 rules.comparisons 声明的跨字段比较。
 * @param {Object} field 当前字段 schema
 * @param {string|number} value 当前字段值
 * @param {Object} values 同一表单作用域内的值
 * @returns {Array<string>} 校验错误文案
 */
export function validateConfiguredFieldComparisons(field = {}, value, values = {}) {
	const configured = field.rules?.comparisons
	const comparisons = Array.isArray(configured)
		? configured
		: configured && typeof configured === 'object'
			? [configured]
			: []
	const errors = []
	for (const rule of comparisons) {
		if (!rule?.fieldKey) continue
		const compared = compareExactDecimals(value, values[rule.fieldKey])
		// 单字段格式校验负责空值和非法数值;比较规则只处理两个合法数值。
		if (compared === null || isComparisonSatisfied(rule.operator, compared)) continue
		errors.push(rule.message || `${field.label || field.key}不满足字段比较规则`)
	}
	return errors
}