Vue 2结合Vee-Validate 3.x坐标输入验证失败求助
解决Vee-Validate 3.x验证坐标格式失效的问题
问题分析
你的两种验证方案都存在细节错误,同时输入限制函数justNumber可能也限制了合法字符的输入,导致验证失效:
1. 修复输入限制函数justNumber
首先确保用户能输入合法的坐标字符(负号-、小数点.、逗号,),同时限制重复符号:
justNumber(e) { const allowedChars = ['0','1','2','3','4','5','6','7','8','9','.',',','-']; if (!allowedChars.includes(e.key)) { e.preventDefault(); return; } const value = e.target.value; const cursorPos = e.target.selectionStart; // 限制单个逗号 if (e.key === ',' && value.includes(',')) { e.preventDefault(); return; } // 限制每个坐标部分只能有一个负号(且在开头) if (e.key === '-') { const parts = value.split(','); const currentPartIndex = cursorPos <= (parts[0]?.length || 0) ? 0 : 1; if (parts[currentPartIndex]?.includes('-')) { e.preventDefault(); return; } } // 限制每个坐标部分只能有一个小数点 if (e.key === '.') { const parts = value.split(','); const currentPartIndex = cursorPos <= (parts[0]?.length || 0) ? 0 : 1; if (parts[currentPartIndex]?.includes('.')) { e.preventDefault(); } } }
2. 修复第一种验证方案
原方案中Number.isFinite(coord)接收的是字符串,会直接返回false,需改为转换为数字后再判断:
extend("coordinates_validation", { validate: (value) => { // 空值根据需求决定是否通过,如需必填请配合`required`规则 if (!value) return true; const coordinates = value.split(","); if (coordinates.length !== 2) return false; const trimmedCoords = coordinates.map(coord => coord.trim()); // 排除空的坐标部分(如",123"或"123,") if (trimmedCoords.some(coord => coord === "")) return false; const isValidCoord = (coord) => { const num = parseFloat(coord); return !Number.isNaN(num) && Number.isFinite(num); }; return trimmedCoords.every(isValidCoord); }, message: i18n.tc("validations.coordinates_incorrect_format"), });
3. 修复第二种正则验证方案
原正则仅支持正整数/浮点数,未考虑负数,同时不支持.123或123.这类合法浮点数格式,修复后的正则如下:
extend('coordinates_validation', { validate: (value) => { // 空值根据需求决定是否通过 if (!value) return true; // 支持正负整数、标准浮点数,以及.xxx/xxx.格式的浮点数 const regex = /^(-?\d+(\.\d*)?|-?\.\d+),\s*(-?\d+(\.\d*)?|-?\.\d+)$/; return regex.test(value); }, message: i18n.tc('validations.coordinates_incorrect_format'), });
额外检查
- 确保
ValidationProvider已正确在Vue实例中注册,extend方法已从vee-validate导入。 - 确认
positionValue是基于最新输入值动态生成的,保证验证的是当前输入框内容。
内容的提问来源于stack exchange,提问作者Jakub Najvárek
相关产品推荐
相关产品推荐

