Home > Net >  Validate TextFormField from another class
Validate TextFormField from another class

Time:03-21

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),
    );
  }
}

CodePudding user response:

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';
                             }
)

CodePudding user response:

You can solve this issue by passing the TextEditingController object to the second class and assigning that object to the TextFormField of the second class, now when you click on submit button in the first class, you have the TextEditingController object so you can check that object data and apply logic on that.

  • Related