Sky Lurk
Sky Lurk

Reputation: 479

Form validation in flutter passes despite not meeting conditions

I am building a Flutter application with multiple TextFormFields. I create a reusable TextFormfield Widget to keep things modular. The problem is, when the submit button is clicked, even though the Text Form Fields are not valid, it runs like it is valid.

My TextFormField widget:

class AndroidTextField extends StatelessWidget {
  final ValueChanged<String> onChanged;
  final String Function(String?)? validator;
  const AndroidTextField(
      {Key? key,
      required this.onChanged,
      this.validator})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return Container(
      width: size.width * .9,
      child: TextFormField(
        validator: validator,
        onChanged: onChanged,
    );
  }
}

How I use it in the Scaffold

                        AndroidTextField(
                            validator: (value) {
                              if (value == null || value.isEmpty) {
                                return 'Enter a valid name';
                              }
                              return '';
                            },
                            onChanged: (val) {
                              setState(() {
                                lastName = val;
                              });
                            }),

The form

  final _formKey = GlobalKey<FormState>();
  @override
   Widget build(BuildContext context) {
    return Scaffold(
     body: Form(
        key: _formKey, 
        AndroidTextField(
            validator: (value) {
               if (value == null || value.isEmpty) {
               return 'Enter a valid name';
               }
               return '';
          },
            onChanged: (val) {
            setState(() {
            firstName = val;
            });
            }),

       TextButton(
         child: Text('Press),
         onPressed:(){
            if (_formKey.currentState!.validate()){
                  //do something
            }else{
                 //don't do the something
            }

        }
      ));

     }

Upvotes: 0

Views: 638

Answers (1)

Dabbel
Dabbel

Reputation: 2825

I feel a flutter validator should return null if valid, not an empty String.

So the code should be:

AndroidTextField(
 validator: (value) {
   if (value == null || value.isEmpty) {
     return 'Enter a valid name';
   }
   return null;
 }
...

Also, try:

final String? Function(String?) validator;

instead of

final String Function(String?)? validator;

Upvotes: 2

Related Questions