Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate TextFormField from another class

I have 2 statefull class, first class contains TextFormField and button to validate the TextFormField. And the second class contains TextFormField.

How to validate second TextFormField thats called in first class when tap the button?

class FormValidation extends StatefulWidget {
  const FormValidation({Key key}) : super(key: key);

  @override
  _FormValidationState createState() => _FormValidationState();
}

class _FormValidationState extends State<FormValidation> {
  final _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: Form(
          key: _formKey,
          child: Column(
            children: [
              TextFormField(
                validator: (value) =>
                    value.isEmpty ? 'Field 1 cannot be Empty' : null,
              ),
              SecondForm(),
              ElevatedButton(
                  onPressed: () {
                    if (_formKey.currentState.validate()) {
                      print('DataSubmitted');
                    }
                  },
                  child: Text('Submit'))
            ],
          ),
        ),
      ),
    );
  }
}

and the second form

class SecondForm extends StatefulWidget {
  const SecondForm({Key key}) : super(key: key);

  @override
  _SecondFormState createState() => _SecondFormState();
}

class _SecondFormState extends State<SecondForm> {
  final _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Form(
      key: _formKey,
      child: TextFormField(
          validator: (value) =>
              value.isEmpty ? 'Field 2 cannot be Empty' : null),
    );
  }
}
like image 267
Soveyyy Avatar asked Mar 18 '26 19:03

Soveyyy


1 Answers

add this on secondForm class, updated the validator with function widget

final Function(String)? validators; //initialization 

validator: widget.validators as String? Function(String?)?,

inside the FormValidation class call this function ,like this way

SecondForm(
validators: (String? value) {
           if (value!.isEmpty)
                return 'Required field';
                             }
)

like image 82
Jinto Joseph Avatar answered Mar 21 '26 10:03

Jinto Joseph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!