You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter TextField内容校验:如何限制输入值不超过指定金额?

实现TextFormField金额上限校验

要实现输入值不超过指定金额(比如$4000)的校验,可以从提交时校验和实时输入限制两方面入手,以下是修改后的完整代码:

// 自定义输入格式化器,用于实时限制输入值不超过上限
class MaxValueInputFormatter extends TextInputFormatter {
  final int maxValue;

  MaxValueInputFormatter(this.maxValue);

  @override
  TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
    // 移除输入中的空格,避免干扰数值判断
    final cleanedText = newValue.text.replaceAll(' ', '');
    
    if (cleanedText.isEmpty) return newValue;
    
    // 转换为数字并判断是否超过上限
    final num? inputValue = int.tryParse(cleanedText);
    if (inputValue != null && inputValue > maxValue) {
      // 超过上限则保留旧值,不允许输入
      return oldValue;
    }
    
    // 限制输入长度不超过最大值的位数(比如4000是4位,最多输入4位数字)
    if (cleanedText.length > maxValue.toString().length) {
      return oldValue;
    }
    
    return newValue;
  }
}

// 修改后的TextFormField
TextFormField(
  decoration: InputDecoration(
    hintStyle: TextStyle(
      fontFamily: "Proxima Nova",
      fontWeight: FontWeight.w300,
    ),
    border: InputBorder.none,
    labelStyle: TextStyle(
      color: Color(0xffFAFAFA),
    ),
  ),
  inputFormatters: [
    FilteringTextInputFormatter.allow(RegExp(r"[0-9]+|\s")),
    // 添加自定义的上限限制格式化器,传入最大值4000
    MaxValueInputFormatter(4000),
  ],
  controller: kiloMeter,
  validator: (value) {
    if (value == null || value.trim().isEmpty) {
      return 'Please enter the price you want to purchase';
    }
    
    // 移除空格并转换为数字
    final cleanedValue = value.trim();
    final num? inputNum = int.tryParse(cleanedValue);
    
    if (inputNum == null) {
      return 'Please enter a valid number';
    }
    
    if (inputNum > 4000) {
      return 'Price cannot exceed \$4000';
    }
    
    return null;
  },
) : const SizedBox(height: 120);

关键修改说明:

  • 实时输入限制:通过自定义MaxValueInputFormatter,在用户输入过程中直接拦截超过4000的数值,同时限制输入位数,避免无效输入。
  • 提交时校验优化:修复原validator的逻辑错误,先判断空值,再校验输入是否为有效数字,最后判断是否超过金额上限,给出明确错误提示。
  • 空格处理:统一移除输入中的空格,避免空格干扰数值判断逻辑。

内容的提问来源于stack exchange,提问作者WonderingDino

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 18:45:22