简体   繁体   English

我想确保用户只能在 TextFormField Flutter 中输入 1 - 10 的数字

[英]I want to make sure that users can put numbers only from 1 - 10 in TextFormField Flutter

This is the code for the textformfield I want to restrict.这是我要限制的 textformfield 的代码。 Users should only be able to enter values from 1-10 but I cant find how to implement that用户应该只能输入 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",
                ),
              ),

you can update your validator function as follows您可以按如下方式更新您的验证器 function


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

   return null;
},

you can try with form and for digit validation, you need to parse the string to int您可以尝试使用表单和数字验证,您需要将字符串解析为 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'),
            )
          ],
        ),
      )

if you want to check the given string is a less than 11 you can do it with the help you a validator.如果你想检查给定的字符串是否小于 11,你可以在验证器的帮助下完成。 but when using a validator you need to perform a trigger or an event need to take place If you want to run your code that way you can use this code...但是当使用验证器时,您需要执行触发器或需要发生事件如果您想以这种方式运行代码,您可以使用此代码...

Code with using validator(Using tigger or even)使用验证器的代码(使用 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")),
              ),
            ),
          )
        ]),
      ),
    );
  }
}

If you want to check the value in real time如果要实时检查值

you can't use a validator you need to restrict your input value the only way to do that is using inputFormatters:您不能使用需要限制输入值的验证器,唯一的方法是使用inputFormatters:

in your case you are using inputFormatter as:在您的情况下,您将 inputFormatter 用作:

 inputFormatters: <TextInputFormatter>[
              FilteringTextInputFormatter.digitsOnly
            ], 

which will only input digits只会输入数字

If you want to input a restricted number you need to make use of Regex如果要输入受限数字,则需要使用Regex

for that change your为此改变你的

inputFormatters: <TextInputFormatter>[
              FilteringTextInputFormatter.digitsOnly
            ], 

to


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

This will help you to only enter only numbers from 1 to 10: -这将帮助您仅输入 1 到 10 之间的数字:-

RegExp("^(1[0-0]|[1-9])$")正则表达式("^(1[0-0]|[1-9])$")

**Full code ** **完整代码**

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")),
              ),
            ),
          )
        ]),
      ),
    );
  }
}

inside the inputFormatters : you simply put below express and this should work...inputFormatters内:您只需在 express 下方放置,这应该可以工作...

// regex expression to accept number only from 1-10 // 正则表达式只接受 1-10 的数字

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我可以将复选框和 textformfield 与 flutter 对齐吗? - Can I put the checkbox and textformfield in line with flutter? 如何在 TextFormField Flutter 中放置 1 个图标和 1 个图标按钮 - How can i put 1 icon and 1 iconbutton in TextFormField Flutter 限制我从用户获取数字到 Flutter 中的 textFormField 的值 - To limit the values ​that I am getting numbers from user into textFormField in Flutter 如何使 TextFormField 的初始值等于从共享首选项加载的变量? (扑) - How can I make the initial value of a TextFormField equal to a variable loaded from shared preferences? (Flutter) 我想验证 flutter 中的“文本”不是(TextFormField 或 Textfield) - I want to validate "Text" in flutter not (TextFormField or Textfield) 当我在颤抖中按下RaisedButton时,我想从TextFormField中获取值 - I want to get the value from a TextFormField when i press a RaisedButton in flutter 如何在 TextFormField (Flutter) 中使用 AppLocalization - How can I use AppLocalization in TextFormField (Flutter) Flutter 中只有数字的 TextFormField - Digit only TextFormField in Flutter 我想在 Flutter 中验证我的 textFormField 而不改变装饰 - I want to validate my textFormField in Flutter without changing the decoration 如果我想将高度设置为 10px 或 10%,那么我应该如何使用它? - In flutter if i want to put height 10px or 10% so how should i used it?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM