Flutter中TextFormField前导零及特殊字符输入限制问题求助
解决Flutter TextFormField的输入限制问题
问题分析
你原来的代码有两个关键问题:
FilteringTextInputFormatter.allow的正则包含了.,所以会允许输入点号;另外你要禁止的?等特殊字符,虽然[0-9.]理论上不允许,但直接把正则改成只允许数字能彻底杜绝这类问题。- 处理前导零的
deny正则r'^0+(?=.)'仅针对零后面跟着点的场景,完全不符合你要去掉数字前导零的需求,所以根本起不到作用。
解决方案
替换你的inputFormatters为以下代码:
首先定义一个自定义输入格式化器处理前导零逻辑:
class LeadingZeroFormatter extends TextInputFormatter { @override TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) { if (newValue.text.isEmpty) return newValue; // 保留单个0的情况 if (newValue.text == '0') return newValue; // 去除所有前导零 String processedText = newValue.text.replaceFirst(RegExp(r'^0+'), ''); // 如果去除后为空(比如输入多个0),则保留一个0 if (processedText.isEmpty) processedText = '0'; // 修正光标位置,避免输入时光标错位 int cursorOffset = newValue.selection.end - (newValue.text.length - processedText.length); cursorOffset = cursorOffset.clamp(0, processedText.length); return TextEditingValue( text: processedText, selection: TextSelection.collapsed(offset: cursorOffset), ); } }
然后在TextFormField中使用:
TextFormField( inputFormatters: [ // 只允许输入数字,直接过滤所有特殊字符 FilteringTextInputFormatter.allow(RegExp(r'[0-9]')), // 处理前导零逻辑 LeadingZeroFormatter(), ], // 其他属性... )
效果验证
- 输入单个
0:正常保留; - 输入
099:自动转为99; - 输入
?、.等特殊字符:直接无法输入; - 输入
000:自动转为0。
内容的提问来源于stack exchange,提问作者vandet
相关产品推荐
相关产品推荐

