11

How to autovalidate a text form field when its value changes?

i tried

bool _autoValidate = false;
TextFormField(
                autovalidate: _autoValidate ,
                onChanged: (value) {
                  setState(() {
                    _autoValidate = true;
                  });
                },
                validator: (value) {
                  if (value.length < 5) {
                    return 'False';
                  } else {
                    return 'True';
                  }
                },
              ),

But not working, TextFormField still doesn't show errors on validation.

I need a way to turn on the validation on text changed.

15
  • I checked your code. It is giving me true after i enter 5 digits Commented Oct 3, 2020 at 8:56
  • stop your app and run it again. Don't hot reload it Commented Oct 3, 2020 at 8:57
  • try to stop running your app and run flutter clean in cmd/terminal Commented Oct 3, 2020 at 9:01
  • @Maz341 it's gives true but still doesn't show errors!! there no red border or the texthint of error Commented Oct 3, 2020 at 9:08
  • @Uni I did flutter clean and still no erros shows, even the _autoValidate var is true, the validation still not working Commented Oct 3, 2020 at 9:12

1 Answer 1

33

Flutter has now an API to validate a form field only when the content changes. You just need to use the autovalidateMode parameter and set it to AutovalidateMode.onUserInteraction.

The following text field will only validate when the user changes its content:

    class HomeScreen extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(),
          body: Center(
            child: TextFormField(
              autovalidateMode: AutovalidateMode.onUserInteraction,
            ),
          ),
        );
      }
    }

See AutovalidateMode docs for more options in when to validate.

This API is now available on the latest stable channel. Let me know if it solves your problem.

Sign up to request clarification or add additional context in comments.

8 Comments

it's needs import or something?
The named parameter 'autovalidateMode' isn't defined. Try correcting the name to an existing named parameter's name, or defining a named parameter with the name 'autovalidateMode'.
flutter --version Flutter 1.20.4 • channel stable
You need to upgrade to the latest stable channel, it is now 1.22.X. Just run: flutter upgrade
nope, the errors is fixed now after restart the vs code many times
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.