如何为FormKit字段添加自定义实时输入掩码?
为FormKit字段添加自定义邮政编码掩码
要实现输入时自动格式化邮政编码(比如输入123456变为12345-6),同时避免无限递归,你可以通过监听FormKit的@input事件,结合仅在值需要变更时才更新的逻辑来实现,核心是切断不必要的更新循环。
直接实现代码
<template> <FormKit type="text" name="postalcode" label="Postal Code" placeholder="Insert a postal code" validation="required|length:9|matches:/^\d{5}\-\d{3}$/" @input="handlePostalCodeInput" /> </template> <script setup> const handlePostalCodeInput = (e) => { const inputEl = e.target; // 过滤掉所有非数字字符,只保留用户输入的原始数字 const rawValue = inputEl.value.replace(/\D/g, ''); // 根据长度生成格式化后的内容 let formattedValue = ''; if (rawValue.length > 5) { formattedValue = `${rawValue.slice(0,5)}-${rawValue.slice(5,8)}`; } else { formattedValue = rawValue; } // 仅当格式化后的值和当前输入框内容不同时才更新,避免递归触发input事件 if (formattedValue !== inputEl.value) { inputEl.value = formattedValue; // 手动触发input事件,让FormKit同步表单值,保证校验逻辑正常运行 inputEl.dispatchEvent(new Event('input', { bubbles: true })); } }; </script>
关键逻辑说明
- 过滤非数字字符:排除掩码符号的干扰,只基于用户输入的纯数字处理格式。
- 条件更新:只有当格式化结果和当前输入值不一致时才执行更新,彻底避免递归循环。
- 手动同步表单:更新输入框后触发
input事件,确保FormKit的表单值和校验逻辑同步。
复用性方案:封装成FormKit插件
如果需要在多个字段复用该掩码逻辑,可以封装成插件:
// postalCodeMask.js export default function postalCodeMask() { return function (node) { // 仅对name为postalcode的字段生效 if (node.props.name === 'postalcode') { node.on('input', (e) => { const inputEl = e.target; const rawValue = inputEl.value.replace(/\D/g, ''); const formattedValue = rawValue.length > 5 ? `${rawValue.slice(0,5)}-${rawValue.slice(5,8)}` : rawValue; if (formattedValue !== inputEl.value) { inputEl.value = formattedValue; inputEl.dispatchEvent(new Event('input', { bubbles: true })); } }); } }; }
在组件中注册并使用:
<template> <FormKit type="text" name="postalcode" label="Postal Code" placeholder="Insert a postal code" validation="required|length:9|matches:/^\d{5}\-\d{3}$/" /> </template> <script setup> import { useFormKit } from '@formkit/vue'; import postalCodeMask from './postalCodeMask.js'; useFormKit().plugin(postalCodeMask); </script>
内容的提问来源于stack exchange,提问作者Wanderson Silva
相关产品推荐
相关产品推荐

