flutterdartvalidationcontrollertextformfield

Flutter - How to generate validation errors in text fields?


I'm creating the 'Create Account' page. It contains the following text fields "First Name, Last Name, Email, Password".

If that field is empty, it will display a validation error above the text form field.

I tried. But I got only a validated message in the terminal output.

I want that error displayed in the application. How to achieve this?

Sample Code:

createAccount(){
    productController.createaccount(
      _emailController.text, _passwordController.text, _firstnameController.text, _lastnameController.text,
      );
  }
              Padding(
                padding: const EdgeInsets.only(top: 35),
                child: Container(
                  width: 310,
                  child: TextFormField(
                    controller: _firstnameController,
                    decoration: InputDecoration(
                      label: RichText(
                        text: TextSpan(
                            text: 'First Name',
                            style: GoogleFonts.poppins(
                                color: Color(0xffc1c1c1),
                                fontSize: 17,
                                letterSpacing: 0.4),
                            children: const [
                              TextSpan(
                                  text: ' *',
                                  style: TextStyle(
                                    color: Colors.red,
                                    fontSize: 21,
                                  )),
                            ]),
                      ),
                    ),
                    validator: (value){
                      if(value!.isEmpty){
                        return 'This field is required';
                      }
                      return null;
                    },
                    
                  ),
                ),
              ),
              Padding(
                padding: const EdgeInsets.only(top: 20),
                child: Container(
                  width: 310,
                  child: TextFormField(
                    controller: _emailController,
                    keyboardType: TextInputType.emailAddress,
                    decoration: InputDecoration(
                      label: RichText(
                        text: TextSpan(
                            text: 'Enter Your Email',
                            style: GoogleFonts.poppins(
                                color: Color(0xffc1c1c1),
                                fontSize: 17,
                                letterSpacing: 0.4),
                            children: const [
                              TextSpan(
                                  text: ' *',
                                  style: TextStyle(
                                    color: Colors.red,
                                    fontSize: 21,
                                  )),
                            ]),
                      ),
                    ),
                    validator: (value){
                      if(value!.isEmpty){
                        return 'This field is required';
                      }
                      if(!RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$').hasMatch(value)){
                        return 'Enter a valid email';
                      }
                      return null;
                    },

                  ),
                ),
              ),
              
              ),

Solution

  • You can achieve like this:

    Define your controller and take Globalkey

    TextEditingController _emailController = TextEditingController();
    
      final _loginKey = GlobalKey<FormState>();
    
      @override
      Widget build(BuildContext context) {
    

    Now you need to wrap your Scaffold body to Form widget and define Global key and define autovalidateMode like this:

    body: Form(
            key: _loginKey,
            autovalidateMode: AutovalidateMode.onUserInteraction,
    child: Column..
    

    That after validate global key on button tap like this::

    TextFormField(
                  controller: _emailController,
                  keyboardType: TextInputType.emailAddress,
                  decoration: InputDecoration(
                    label: RichText(
                      text: TextSpan(text: 'Enter Your Email', children: const [
                        TextSpan(
                            text: ' *',
                            style: TextStyle(
                              color: Colors.red,
                              fontSize: 21,
                            )),
                      ]),
                    ),
                  ),
                  validator: (value) {
                    if (value!.isEmpty) {
                      return 'This field is required';
                    }
                    if (!RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$').hasMatch(value)) {
                      return 'Enter a valid email';
                    }
                    return null;
                  },
                ),
    
                ElevatedButton(
                    onPressed: () {
                      if (_loginKey.currentState?.validate() == true) {
                        //Navigate to another screen
                      } else {}
                    },
                    child: Text('Login'))
    

    Output:

    enter image description here