Flutter Text Field Material Design and Form Validation with MultiValidation

Flutter Validation Input form

Form Validation is an important part of every application. In the flutter application, there are many ways to validate forms such as using a TextEditingController. In this Topic, we are using form_field_validator package for the validators text form.


Creating a form in Flutter

First, we are going to create a simple form page that has the following fields:

  • Name
  • Email
  • Password




For the validation, we want the users of our app to fill in the correct details in each of these fields. The logic will be defined as such:

First, for the name field, we want the user to enter a min 6 Characters and max 20 Characters, which can be accompanied by initials.

For the email field, we want a valid email that contains some characters before the “@” sign, as well as the email domain at the end of the email.

Finally, for our password validation, we want the user to enter a min 6 Characters and max 15 Characters, which can be accompanied by initials.











Setting up a form to validate

Start by creating a new Flutter project in either of VS Code or Android Studio. Replace the Flutter default counter application in main.dart with your own stateful widget.

You should have something like this:

import 'package:flutter/material.dart';
import 'package:formvalidation/form/form.dart';
void main() {
  runApp(const MyApp());
}
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: FormValidation()
    );
  }
}


This is what our main.dart file looks like currently. Now, create a new dart file and name it form.dart in form folder,  then create the FormValidation stateful widget inside of it with the following code:

import 'package:flutter/material.dart';
import 'package:form_field_validator/form_field_validator.dart';

class FormValidation extends StatefulWidget {
  const FormValidation({Key? key}): super(key:key);
  @override
  _FormValidationState createState() => _FormValidationState();
}
class _FormValidationState extends State<FormValidation>{
  GlobalKey<FormState> formkey = GlobalKey<FormState>();
  void onSubmit() {
    if(formkey.currentState!.validate()){
        print("submit");
    }
  }
  
  @override
  Widget build(BuildContext context){
    return Scaffold(
      backgroundColor: Colors.white,
      body: SafeArea(
        child: Form(
          key:formkey,
          child: Container(
            padding: EdgeInsets.all(20),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    TextFormField(
                        decoration: InputDecoration(
                          labelText: "Name",
                          labelStyle: TextStyle(fontSize: 14, color: Colors.blue),
                          enabledBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10),
                            borderSide: BorderSide(
                              color: Colors.blue
                            )
                          ),
                          focusedBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(10),
                              borderSide: BorderSide(
                                  color: Colors.blue
                              )
                          ),
                          focusedErrorBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(10),
                              borderSide: BorderSide(
                                  color: Colors.red
                              )
                          ),
                          errorBorder:  OutlineInputBorder(
                              borderRadius: BorderRadius.circular(10),
                              borderSide: BorderSide(
                                  color: Colors.red
                              )
                          ),
                          border:  OutlineInputBorder(
                              borderRadius: BorderRadius.circular(10),
                              borderSide: BorderSide(
                                  color: Colors.blue
                              )
                          ),
                        ),
                      validator: MultiValidator([
                        RequiredValidator(errorText: "Name Required"),
                        MinLengthValidator(4, errorText: "Name should be atleast 6 character"),
                        MaxLengthValidator(20, errorText: "Name should not be greater then 20 character")
                      ]),
                    ),
                    SizedBox(
                      height: 20,
                    ),
                    TextFormField(
                      decoration: InputDecoration(
                        labelText: "Email",
                        labelStyle: TextStyle(fontSize: 14, color: Colors.blue),
                        enabledBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10),
                            borderSide: BorderSide(
                                color: Colors.blue
                            )
                        ),
                        focusedBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10),
                            borderSide: BorderSide(
                                color: Colors.blue
                            )
                        ),
                        focusedErrorBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10),
                            borderSide: BorderSide(
                                color: Colors.red
                            )
                        ),
                        errorBorder:  OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10),
                            borderSide: BorderSide(
                                color: Colors.red
                            )
                        ),
                        border:  OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10),
                            borderSide: BorderSide(
                                color: Colors.blue
                            )
                        ),
                      ),
                      validator: MultiValidator([
                        RequiredValidator(errorText: "Email Required"),
                        EmailValidator(errorText: "Enter valid email")
                      ]),
                    ),

                    SizedBox(
                      height: 20,
                    ),
                    TextFormField(
                      obscureText: true,
                      decoration: InputDecoration(
                        labelText: "Password",
                        labelStyle: TextStyle(fontSize: 14, color: Colors.blue),
                        enabledBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10),
                            borderSide: BorderSide(
                                color: Colors.blue
                            )
                        ),
                        focusedBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10),
                            borderSide: BorderSide(
                                color: Colors.blue
                            )
                        ),
                        focusedErrorBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10),
                            borderSide: BorderSide(
                                color: Colors.red
                            )
                        ),
                        errorBorder:  OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10),
                            borderSide: BorderSide(
                                color: Colors.red
                            )
                        ),
                        border:  OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10),
                            borderSide: BorderSide(
                                color: Colors.blue
                            )
                        ),
                      ),
                      validator: MultiValidator([
                        RequiredValidator(errorText: "Email Password"),
                        MinLengthValidator(6, errorText: "Password should be atleast 6 character"),
                        MaxLengthValidator(15, errorText: "Password should not be greater then 15 character")
                      ]),
                    ),
                    SizedBox(
                      height: 30,
                    ),
                    ElevatedButton(
                      onPressed: () {
                        onSubmit();
                      },
                      child: Text("Thank you and support us"),
                    )
                  ],
                )
              ],
            ),
          ),
        )
      ),
    );
  }
}

Following properties:

  • labelText, which provides label text to be shown before any input
  • validator, a function that validates our input when instructed
  • obscureText, which is using the password field
  • InputDecoration, which provides the border, labels, icons, and styles used to decorate a Material Desing text field.
  • Validator, which provides the validator to return an error string (or null) based on the input text

The way we trigger the validation on this page is by using the form key variable we created to give us access to the state of our form:


   ElevatedButton(

          onPressed: () {

               onSubmit();

         },

          child: Text("Thank you and support us"),

    )


   void onSubmit() {

    if(formkey.currentState!.validate()){

        print("submit");

    }

   }


So, whenever a user clicks on the button, we check _formKey.currentState!.validate(), then we carry out an action, which, in our case, would be simply navigating to a new screen.

Your success page can be anything or any screen you want to take the user to after completing the field validation and using the data entered by the user.

When submit button is pressed, we see the following error message for an image upload.


Flutter Validation Input form
Comments

AdBlock Detected!

Our website is made possible by displaying ads to our visitors. Please supporting us by whitelisting our website.