lathrix
lathrix

Reputation: 125

How to validate TextFormField individually using onFieldSubmitted

I'm making a custom TextFormField Widget which will be used multiple times. How do I validate a single TextFormField without validating any other TextFormField that are in the same list/row/column.

Widget timeTextField (TextEditingController controller){
       return TextFormField(
         controller: controller,
         validator: (String userInput){
           if(userInput.isEmpty){return 'Need to input time';}
         },
         onFieldSubmitted: (String userInput){
           setState(() {
             debugPrint(userInput);
             controller.text = "amout";
             debugPrint(controller.text);
         });

   },
   );
 }

It validates when the user presses submit on the keyboard, if the TextFormField is empty it sends a validation error only to that TextFormField which the user pressed submit on.

Upvotes: 9

Views: 11058

Answers (2)

Anoop Thiruonam
Anoop Thiruonam

Reputation: 2872

Just for information on a closed question:

You can use autovalidateMode.

This has currently 3 modes. We used to have autovalidate which is depreciated. This works only on FormFields and inside Forms.

Example

       TextFormField(
                  autocorrect: false,
                  autovalidateMode: AutovalidateMode.onUserInteraction,
                  cursorColor: Colors.black,
                  key: _usernameKey,

Reference

  • Flutter official docs

Upvotes: 12

Ajil O.
Ajil O.

Reputation: 6892

Validation in TextFields happen based on the Form they are placed in (and not Column or Row or List). To validate TextFields separately put them in different forms, assign different keys and call _formKey.currentState.validate separately.

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final GlobalKey<FormState> _form1Key = GlobalKey();
    final GlobalKey<FormState> _form2Key = GlobalKey();
    final GlobalKey<FormState> _form3Key = GlobalKey();

    return Scaffold(
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Form(
            key: _form1Key,
            child: TextFormField(
              validator: (value) {
                if (value.isEmpty) return "Cannot be empty";
              },
            ),
          ),
          Form(
            key: _form2Key,
            child: TextFormField(
              validator: (value) {
                if (value.isEmpty) return "Cannot be empty";
              },
            ),
          ),
          Form(
            key: _form3Key,
            child: TextFormField(
              validator: (value) {
                if (value.isEmpty) return "Cannot be empty";
              },
            ),
          ),
        ],
      ),
      floatingActionButton: FloatingActionButton(onPressed: () {
        _form2Key.currentState.validate();
      }),
    );
  }
}

Upvotes: 13

Related Questions