简体   繁体   English

Flutter 中的文本字段验证

[英]Textfield validation in Flutter

I am working on Flutter TextField widget.我正在研究 Flutter TextField小部件。 I want to show an error message below the TextField widget if the user does not fill that TextField .如果用户没有填写该TextField我想在TextField小部件下方显示一条错误消息。 I only have to use TextField Widget not TextFormField in this case.在这种情况下,我只需要使用TextField小部件而不是TextFormField

A Minimal Example of what you Want:您想要的最小示例:

class MyHomePage extends StatefulWidget {
  @override
  MyHomePageState createState() {
    return new MyHomePageState();
  }
}

class MyHomePageState extends State<MyHomePage> {
  final _text = TextEditingController();
  bool _validate = false;

  @override
  void dispose() {
    _text.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('TextField Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('Error Showed if Field is Empty on Submit button Pressed'),
            TextField(
              controller: _text,
              decoration: InputDecoration(
                labelText: 'Enter the Value',
                errorText: _validate ? 'Value Can\'t Be Empty' : null,
              ),
            ),
            RaisedButton(
              onPressed: () {
                setState(() {
                  _text.text.isEmpty ? _validate = true : _validate = false;
                });
              },
              child: Text('Submit'),
              textColor: Colors.white,
              color: Colors.blueAccent,
            )
          ],
        ),
      ),
    );
  }
}

Flutter handles error text itself, so we don't require to use variable _validate . Flutter 本身会处理错误文本,因此我们不需要使用变量_validate It will check at runtime whether you satisfied the condition or not.它会在运行时检查您是否满足条件。

final confirmPassword = TextFormField(
  controller: widget.confirmPasswordController,
  obscureText: true,
  decoration: InputDecoration(
    prefixIcon: Icon(Icons.lock_open, color: Colors.grey),
    hintText: 'Confirm Password',
    errorText: validatePassword(widget.confirmPasswordController.text),
    contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
  ),
);

String validatePassword(String value) {
  if (!(value.length > 5) && value.isNotEmpty) {
    return "Password should contain more than 5 characters";
  }
  return null;
}

Note : User must add at least one character to get this error message.注意:用户必须至少添加一个字符才能获得此错误消息。

I would consider using a TextFormField with a validator .我会考虑使用带有validatorTextFormField

Example:例子:

class MyHomePageState extends State<MyHomePage> {
  final _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('TextFormField validator'),
      ),
      body: Form(
        key: _formKey,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            TextFormField(
              decoration: InputDecoration(
                hintText: 'Enter text',
              ),
              textAlign: TextAlign.center,
              validator: (text) {
                if (text == null || text.isEmpty) {
                  return 'Text is empty';
                }
                return null;
              },
            ),
            RaisedButton(
              onPressed: () {
                if (_formKey.currentState.validate()) {
                  // TODO submit
                }
              },
              child: Text('Submit'),
            )
          ],
        ),
      ),
    );
  }
}
  • If you use TextFormField then you could easily implement 'Error below your text fields'.如果您使用TextFormField那么您可以轻松实现“文本字段下方的错误”。
  • You can do this without using _validate or any other flags.您可以在不使用_validate或任何其他标志的情况下执行此操作。
  • In this example, I have used validator method of TextFormField widget.在这个例子中,我使用了TextFormField小部件的validator方法。 This makes the work a lot more easier and readable at the same time.这使工作同时变得更加容易和可读。
  • I also used FormState to make the work more easier我还使用了FormState使工作更轻松
void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  final _form = GlobalKey<FormState>(); //for storing form state.

//saving form after validation  
void _saveForm() {
    final isValid = _form.currentState.validate();
    if (!isValid) {
      return;
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Form(
          key: _form, //assigning key to form

          child: ListView(
            children: <Widget>[

              TextFormField(
                decoration: InputDecoration(labelText: 'Full Name'),
                validator: (text) {
                  if (!(text.length > 5) && text.isNotEmpty) {
                    return "Enter valid name of more then 5 characters!";
                  }
                  return null;
                },
              ),

              TextFormField(
                decoration: InputDecoration(labelText: 'Email'),
                validator: (text) {
                  if (!(text.contains('@')) && text.isNotEmpty) {
                    return "Enter a valid email address!";
                  }
                  return null;
                },
              ),

              RaisedButton(
                child: Text('Submit'),
                onPressed: () => _saveForm(),
              )
            ],
          ),
        ),
      ),
    );
  }
}

I hope this helps!我希望这有帮助!

You can do something like this你可以做这样的事情

class _validateTextField extends State<validateTextField> {
  TextEditingController userNameController = TextEditingController();
  bool userNameValidate = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
          child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                TextField(
                  controller: userNameController,
                  decoration: InputDecoration(
                      labelText: 'Enter Username',
                      errorText: isUserNameValidate ? 'Please enter a Username' : null
                  ),
                ),
                SizedBox(height: 50,),
                OutlineButton(
                  onPressed: () {
                    validateTextField(userNameController.text);
                  },
                  child: Text('Validate'),
                  textColor: Colors.blue,
                ),
              ]
          )
      ),
    );
  }
}

Create Function - This function will validate whether the value you entered is validate or not.创建函数 - 此函数将验证您输入的值是否有效。 And call it at the click of a submit or validate button并在单击提交或验证按钮时调用它

  bool validateTextField(String userInput) {
    if (userInput.isEmpty) {
      setState(() {
        isUserNameValidate = true;
      });
      return false;
    }
    setState(() {
      isUserNameValidate = false;
    });
    return true;
  }

在此处输入图片说明

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM