【问题标题】:I want to make sure that users can put numbers only from 1 - 10 in TextFormField Flutter我想确保用户只能在 TextFormField Flutter 中输入 1 到 10 的数字
【发布时间】:2021-12-31 16:33:13
【问题描述】:

这是我要限制的 textformfield 的代码。用户应该只能输入 1-10 的值,但我找不到如何实现它

       TextFormField(
                validator: (value) {
                  if (value.isEmpty) {
                    return 'Please enter the Overall Rating';
                  }
                  return null;
                },
                keyboardType: TextInputType.number,
                inputFormatters: <TextInputFormatter>[
                  FilteringTextInputFormatter.digitsOnly
                ], // Only numbers can be entered
                maxLength: 2,
                maxLengthEnforced: true,
                controller: overall,
                decoration: InputDecoration(
                    hintText: "Overall Rating  Out of /10",
                ),
              ),

【问题讨论】:

    标签: flutter validation


    【解决方案1】:

    inputFormatters 内:您只需在 express 下方放置,这应该可以工作...

    // 正则表达式只接受 1-10 的数字

    inputFormatters: [  
    FilteringTextInputFormatter.allow(RegExp(r'^[1-9]$|^10$'),
    ),],
    

    【讨论】:

      【解决方案2】:

      如果你想检查给定的字符串是否小于 11,你可以在验证器的帮助下完成。但是当使用验证器时,您需要执行触发器或需要发生事件 如果您想以这种方式运行您的代码,您可以使用此代码...

      使用验证器的代码(使用 tigger 甚至)

      import 'package:flutter/material.dart';
      import 'package:flutter/services.dart';
      
      class Textfi extends StatelessWidget {
        Textfi({Key? key}) : super(key: key);
        final _formKey = GlobalKey<FormState>();
      
        @override
        Widget build(BuildContext context) {
          return Scaffold(
            body: Form(
              key: _formKey,
              child: Column(children: [
                const SizedBox(
                  height: 70,
                ),
                TextFormField(
                  validator: (value) {
                    if (value!.isEmpty) {
                      return 'Please enter the Overall Rating';
                    } else if (int.parse(value) < 1 || int.parse(value) > 10) {
                      return 'The rating must be between 1 and 10';
                    }
                    return null;
                  },
                  keyboardType: TextInputType.number,
      
                  inputFormatters: <TextInputFormatter>[
                    FilteringTextInputFormatter.digitsOnly
                  ], // Only numbers can be entered
                  maxLength: 2,
                  maxLengthEnforced: true,
      
                  decoration: const InputDecoration(
                    hintText: "Overall Rating  Out of /10",
                  ),
                ),
                GestureDetector(
                  onTap: () {
                    if (_formKey.currentState!.validate()) {
                      ScaffoldMessenger.of(context).showSnackBar(
                        const SnackBar(content: Text('Validation done')),
                      );
                    }
                  },
                  child: Padding(
                    padding: const EdgeInsets.all(20.0),
                    child: Container(
                      height: 30,
                      width: 80,
                      color: Colors.blue,
                      child: const Center(child: Text("Submit")),
                    ),
                  ),
                )
              ]),
            ),
          );
        }
      }
      

      如果要实时查看数值

      您不能使用需要限制输入值的验证器,唯一的方法是使用inputFormatters:

      在您的情况下,您将 inputFormatter 用作:

       inputFormatters: <TextInputFormatter>[
                    FilteringTextInputFormatter.digitsOnly
                  ], 
      

      只输入数字

      如果你想输入一个受限数字,你需要使用Regex

      为此改变你的

      inputFormatters: <TextInputFormatter>[
                    FilteringTextInputFormatter.digitsOnly
                  ], 
      

      
       inputFormatters: <TextInputFormatter>[    
                    FilteringTextInputFormatter.allow(RegExp("^(1[0-0]|[1-9])\$")),
                  ],
      

      这将帮助您只输入从 1 到 10 的数字:-

      RegExp("^(1[0-0]|[1-9])$")

      **完整代码**

      import 'package:flutter/material.dart';
      import 'package:flutter/services.dart';
      
      class Textfi extends StatelessWidget {
        Textfi({Key? key}) : super(key: key);
        final _formKey = GlobalKey<FormState>();
      
        @override
        Widget build(BuildContext context) {
          return Scaffold(
            body: Form(
              key: _formKey,
              child: Column(children: [
                const SizedBox(
                  height: 70,
                ),
                TextFormField(
                  validator: (value) {
                    if (value!.isEmpty) {
                      return 'Please enter the Overall Rating';
                    } else if (int.parse(value) < 1 || int.parse(value) > 10) {
                      return 'The rating must be between 1 and 10';
                    }
                    return null;
                  },
                  keyboardType: TextInputType.number,
                  inputFormatters: <TextInputFormatter>[
                    FilteringTextInputFormatter.allow(RegExp("^(1[0-0]|[1-9])\$")),
                  ],
                  // inputFormatters: <TextInputFormatter>[
                  //   FilteringTextInputFormatter.digitsOnly
                  // ], // Only numbers can be entered
                  maxLength: 2,
                  maxLengthEnforced: true,
      
                  decoration: const InputDecoration(
                    hintText: "Overall Rating  Out of /10",
                  ),
                ),
                GestureDetector(
                  onTap: () {
                    if (_formKey.currentState!.validate()) {
                      ScaffoldMessenger.of(context).showSnackBar(
                        const SnackBar(content: Text('Validation done')),
                      );
                    }
                  },
                  child: Padding(
                    padding: const EdgeInsets.all(20.0),
                    child: Container(
                      height: 30,
                      width: 80,
                      color: Colors.blue,
                      child: const Center(child: Text("Submit")),
                    ),
                  ),
                )
              ]),
            ),
          );
        }
      }
      
      

      【讨论】:

      • 你试过了吗?
      • 非常感谢。这对我有用。为迟到的回应道歉。我的 android studio 给了我问题,所以我不得不重新安装它
      • 你能让这个答案可以接受吗(正确)
      • 当然可以。对于那个很抱歉。我忘了。再次感谢
      • 您能否也为答案投票,以便更多人可以使用答案
      【解决方案3】:

      您可以按如下方式更新您的验证器功能

      
      validator: (value) {
         if (value.isEmpty) {
           return 'Please enter the Overall Rating';
         }
         if(int.parse(value) < 1 || int.parse(value) > 10) {
            return 'The rating must be between 1 and 10';
         }
      
         return null;
      },
      
      

      【讨论】:

      • 它给了我一个错误 '' 。错误是未为类型“String”定义运算符“
      • @SaaimahPatel 我已经更新了答案。
      【解决方案4】:

      您可以尝试使用表单和数字验证,您需要将字符串解析为 int

      Form(
              key: _formKey,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  TextFormField(
                    keyboardType: TextInputType.number,
                    inputFormatters: <TextInputFormatter>[
                      FilteringTextInputFormatter.digitsOnly
                    ],
                    // Only numbers can be entered
                    maxLength: 2,
                    maxLengthEnforced: true,
                    controller: overall,
                    decoration: InputDecoration(
                      hintText: "Overall Rating  Out of /10",
                    ),
                    validator: (text) {
                      if (text == null || text.isEmpty) {
                        return 'Text is empty';
                      }
                      if (int.parse(text) < 1 || int.parse(text) > 10) {
                        return 'The rating must be between 1 and 10';
                      }
                      return null;
                    },
                  ),
                  TextButton(
                    onPressed: () {
                      if (_formKey.currentState.validate()) {
                        // TODO submit
                      }
                    },
                    child: Text('Submit'),
                  )
                ],
              ),
            )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-12-04
        • 2022-10-21
        • 2023-01-28
        • 1970-01-01
        • 2021-06-09
        • 2021-12-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多