如何在JavaScript中通过正则表达式校验输入是否匹配指定掩码与模式
掩码输入组件校验修复方案
现有代码核心问题
- 工具函数逻辑完全失效:
isNumber错误将入参作为函数执行,isLetter中checkIfLetter.toLowerCase() != checkIfLetter.toLowerCase()恒为false,无法完成基础字符类型判断 - 校验规则逻辑错位:
isRightSymbol使用全量正则匹配单个输入字符,且遍历规则时直接返回第一个结果,无法适配不同模式的校验要求 - 逻辑判断顺序错误:
inputFruitName中或、且逻辑未加括号,判断顺序不符合预期 - 数据结构未关联:模式、掩码、校验规则分散定义,缺少当前生效模式的标识,无法确定校验基准
正确实现方案
核心逻辑
- 统一合法字符范围:支持大小写拉丁字母、大小写西里尔字母、数字、空格、短横线、下划线
- 按模式提前映射每一位的字符类型要求:
A对应允许字母/合法特殊字符,1对应允许数字 - 输入时按光标所在位置的规则校验单个字符,不符合要求直接拦截输入
- 输入完成后支持全量格式校验
修复后完整代码
export default { data: () => ({ // 格式定义:A=允许字母/特殊字符,1=允许数字 plate_pattern: { app11le: "AAA11AA", cherr11y: "AAAA11A", a111pricot: "A111AAAAA" }, // 当前生效的模式key,可根据业务切换 currentPatternKey: "app11le", mask: { app11le: " ___ __ __", cherr11y: "____ ___", a111pricot: "_ _______" }, placeholder: '_', inputValue: "", isRight: true }), computed: { // 当前模式的格式规则数组 currentPattern() { return this.plate_pattern[this.currentPatternKey].split("") }, // 当前模式的全量校验正则 currentFullRegex() { const regStr = this.currentPattern.map(type => { if (type === "A") return "[a-zA-Zа-яА-Я\\s\\-_]" if (type === "1") return "\\d" }).join("") return new RegExp(`^${regStr}$`) } }, methods: { // 校验单个字符是否符合当前位置要求 isValidChar(char, position) { if (position >= this.currentPattern.length) return false const requiredType = this.currentPattern[position] if (requiredType === "1") { return /^\d$/.test(char) } if (requiredType === "A") { return /^[a-zA-Zа-яА-Я\s\-_]$/.test(char) } return false }, // 输入事件拦截校验 inputFruitName(e) { const inputChar = e.key // 跳过控制键(删除、回车、方向键等) if (["Backspace", "Delete", "ArrowLeft", "ArrowRight", "Tab"].includes(inputChar)) return // 获取当前光标位置 const cursorPos = e.target.selectionStart // 校验当前位置输入是否合法 if (!this.isValidChar(inputChar, cursorPos)) { e.preventDefault() this.isRight = false return } this.isRight = true }, // 全量校验(提交/失焦时调用) validateFullInput() { this.isRight = this.currentFullRegex.test(this.inputValue) return this.isRight } } }
额外注意事项
- 如果需要支持粘贴输入,可在粘贴事件中获取粘贴内容,调用
currentFullRegex做全量校验,不符合则拦截 - 可根据业务需求扩展字符类型,直接修改
isValidChar中的正则即可
内容的提问来源于stack exchange,提问作者WildHaskyWhiskey
相关产品推荐
相关产品推荐

