Search code examples
flutterdartflutter-form-builder

How to call specific validator instead of calling all the validators in same time by using `form.validate()`?


This is the code :

if (form.validate()) {
          // Text forms was validated.
          if (mounted) {
            setState(() {
              _isButtonEnabled = true;
            });
          }
          form.save();
        }

I want to call specific validator for specific TextFormField


Solution

  • You will need to wrap each field you want to validate individually with a Form Widget and it's own key:

    class TextFormFieldValidation extends StatefulWidget {
      @override
      _TextFormFieldValidationState createState() => _TextFormFieldValidationState();
    }
    
    class _TextFormFieldValidationState extends State<TextFormFieldValidation> {
      List<GlobalKey<FormState>> _formKeysList= [
        GlobalKey<FormState>(),
        GlobalKey<FormState>(),
      ];
    
      @override
      Widget build(BuildContext context) {
        return Column(
          children: <Widget>[
            Form(
              key: _formKeysList[0],
              child: TextFormField(
                validator: (value) => 'Bad',
              ),
            ),
            Form(
              key: _formKeysList[1],
              child: TextFormField(
                validator: (value) => 'Bad',
              ),
            ),
            RaisedButton(
              child: Text('Validate 1'),
              onPressed: () => _formKeysList[0].currentState.validate(),
            ),
            RaisedButton(
              child: Text('Validate 2'),
              onPressed: () => _formKeysList[1].currentState.validate(),
            ),
            RaisedButton(
              child: Text('Reset'),
              onPressed: () => _formKeysList.forEach((key) => key.currentState.reset()),
            ),
          ],
        );
      }
    }