Flutter中实现3位整数1位小数的正则表达式需求
解决方案
要满足你的输入校验要求,需要同时调整inputFormatters(实时限制输入内容)和validator(提交时校验最终值)的规则,确保输入过程中就不会出现无效内容,且最终值严格符合规范:
修改后的完整代码
TextFormField( focusNode: participantHeightFocus, inputFormatters: [ FilteringTextInputFormatter.allow( RegExp(r'^[1-9]\d{0,2}(\.\d?)?$'), ), ], validator: (value) { if (value!.isEmpty) { return "Height is required"; } // 校验最终输入是否完全符合规则 final validFormat = RegExp(r'^[1-9]\d{2}(\.\d)?$'); if (!validFormat.hasMatch(value)) { return "Please enter the height in cm (e.g., 170.0 cm)"; } return null; }, controller: participantHeight, onChanged: (_) => calculateBMIAndUpdate(), decoration: InputDecoration( hintText: "Participant Height (*)", labelText: "Participant Height (*)", labelStyle: const TextStyle(fontSize: 20), border: OutlineInputBorder( borderRadius: BorderRadius.circular(5), ), ), )
关键调整说明
1. 实时输入过滤(inputFormatters)
替换了原来宽松的正则,改用^[1-9]\d{0,2}(\.\d?)?$,它会实时限制:
- 首位不能为0,必须是1-9的数字
- 整数部分最多输入3位
- 小数点后最多输入1位数字(且小数点只能在3位整数之后添加)
这样用户根本无法输入像012、1234、12.22这类无效内容。
2. 最终提交校验(validator)
使用^[1-9]\d{2}(\.\d)?$确保最终输入完全符合规则:
[1-9]\d{2}:强制要求整数部分是3位非0开头的数字(\.\d)?:允许可选的1位小数(支持纯整数如200或带小数如200.0的格式)
这样双重校验后,既能提升输入体验,又能保证提交数据的准确性。
内容的提问来源于stack exchange,提问作者Iman Sarwar
相关产品推荐
相关产品推荐

