Home > Software engineering >  Form validation in flutter passes despite not meeting conditions
Form validation in flutter passes despite not meeting conditions

Time:05-17

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
            }

        }
      ));

     }

CodePudding user response:

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;

  • Related