简体   繁体   English

焦点更改时的 TextFormField 验证

[英]TextFormField validation when focus changes

I am using a form and some TextFormFields.我正在使用一个表单和一些 TextFormFields。 I can validate the user input as below:我可以验证用户输入如下:

final _form = GlobalKey<FormState>();

void saveForm(){

_form.currentState.validate()

}

//saveForm runs when a save button is pressed.

I want to know whether it's possible to run validate function for a TextField when it loses its focus or not.(I don't want to validate the input by clicking a button and instead, I want to run validate function when user changes the TextField.)我想知道是否可以在 TextField 失去焦点时对其运行 validate function。(我不想通过单击按钮来验证输入,而是在用户更改 TextField 时运行 validate function .)

I think you just want to add autovalidate: true, in your form so when your focus is change validation is call我认为您只想在表单中添加autovalidate: true,因此当您的焦点是更改验证时调用

 Form(
         key: _formKey,
         autovalidate: true,
         child:/*...*/
    )

Create your form like创建您的表单,例如

  var _formKey = GlobalKey<FormState>();
  bool _autoValidate = false;

  @override
  Widget build(BuildContext context) {
    return Form(
          key: _formKey,
          autovalidate: _autoValidate,
          child: /* ... */
        ),
      ),
    );
  }

when you click on save当你点击保存

void _onSignUpClicked(BuildContext context) {
    if (_formKey.currentState.validate()) {
      Scaffold.of(context).showSnackBar(SnackBar(content: Text("Successfully sign up")));
    } else {
      setState(() {
        _autoValidate = true;
      });
    }
  }

Put TextEditingController to TextField and use addListener for getting every change.TextEditingController放入TextField并使用addListener来获取每个更改。 And do validate process inside that listener.并在该侦听器内验证过程。

To notice, the accepted solution now is deprecated after 1.19需要注意的是,现在接受的解决方案在1.19之后已弃用
Now, new parameters has been introduced AutovalidateMode with three essential constants:现在,引入了具有三个基本常量的新参数AutovalidateMode

  1. always: Used to auto-validate Form and FormField even without user interaction. always:用于自动验证 Form 和 FormField,即使没有用户交互。
  2. disabled: No auto validation will occur. disabled:不会发生自动验证。
  3. onUserInteraction: Used to auto-validate Form and FormField only after each user interaction. onUserInteraction:用于仅在每次用户交互后自动验证 Form 和 FormField。

Add autoValidateMode to your form将 autoValidateMode 添加到您的表单

autovalidateMode: AutovalidateMode.onUserInteraction, autovalidateMode:AutovalidateMode.onUserInteraction,

child: Form(
      key: _formKey,
      autovalidateMode: AutovalidateMode.onUserInteraction,
      child: Column()
)

Auto validate has two more modes disabled (never auto validate) and always (in all cases even without any user interaction).自动验证有另外两种禁用模式(从不自动验证)和始终(在所有情况下,即使没有任何用户交互)。

Read more over here在这里阅读更多

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

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