top of page

Flutter: Forms and Text Validation

Updated: Nov 27, 2022

Checking and validating forms is an old practice that is followed since the times of the website and we have the same feature in Flutter. Many times user inputs either wrong information or in incorrect format and that's why Form and Text validation is very important whether it is a website or an app. Suppose you want a user to input his / her email address. Now if the user randomly types anything, you will store the wrong information. With Forms in Flutter, this work is even easier.

So in this tutorial, we are going to learn how to validate the Form widget and data input by users.

Approach

We will create a Form with some Text fields in our app. Later we will create a function that will check and validate the information input by the user.



Table of Contents

  • Setup Project

  • Create a Form with Text Fields

  • Validation

  • Conclusion

Setup Project

We can either create a new project or proceed with the existing project. The project does not require any other dependencies to be installed.

Let's begin!

Here is the starter code.


class FormsTutorial extends StatefulWidget {
  const FormsTutorial({Key? key}) : super(key: key);

  @override
  _FormsTutorialState createState() => _FormsTutorialState();
}

class _FormsTutorialState extends State<FormsTutorial> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Forms and Text Validation"),
      ),
      body: Container(
        child: Form(
          child: Column(
            children: [],
          ),
        ),
      ),
    );
  }
}

Here everything is self-explanatory.


We have used a Form widget. To validate a form we need a key. Key is used to maintain the state and also retrieve the information about the current state. But for us, this is required for the validation and return any error if the user types any wrong information.

We will initialize the key before the widget-build function.

final form_key = GlobalKey<FormState>();

Now pass the form_key to the key field of the Form widget.

key: form_key,

Let us create some UI and also text fields to enter some value.

We will use the TextFormField widget in our app because it has the validator function which validates the value entered by the user and returns an error if the information is not in the correct format or else return nothing.


We will place everything inside the Column widget.

Here is our code for the user input and also some decoration.

The decoration is your own choice.



Form(
  key: form_key,
  child: Column(
    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
    children: [
      Text(
        "Enter the details",
        style: TextStyle(
          fontSize: 32.0,
          fontWeight: FontWeight.w600,
        ),
      ),
      TextFormField(
        keyboardType: TextInputType.name,
        decoration: InputDecoration(
          hintText: 'Enter your name',
          labelText: 'Name',
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(10.0),
          ),
        ),
      ),
      TextFormField(
        keyboardType: TextInputType.number,
        decoration: InputDecoration(
          hintText: 'Enter your pincode',
          labelText: 'Pincode',
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(10.0),
          ),
        ),
      ),
      ElevatedButton(
        onPressed: () {},
        child: Text("Submit"),
        style: ElevatedButton.styleFrom(),
      ),
    ],
  ),
),

Run the app and the result will be as follows.




Validation

Let us code our validation process.

First, we need to code our validator for the TextFormField for the name and the pin code fields.

Validator for the name TextFormField.


validator: (value) {
  if (value!.length < 4) return "Enter a valid name";
},

If the number of characters is less than 4, we will return an error asking to write a valid name.

Validator for the Pincode( Pincode for India) TextFormField.


validator: (value) {
  if (value!.length != 6) return "Enter a valid pincode";
},

In India, the length of Pincode is six. So if the length is not equal to six, we will return an error.

Till now, there is no difficulty.

Now we will code our onPressed function of Submit button.

We will validate our form and store the result. Validation returns a boolean value. And if valid we will process further.

Here is the syntax for our code.



onPressed: () {
  final isValid = form_key.currentState!.validate();
  if (isValid) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(
          "Welcome to AllAboutFlutter",
        ),
      ),
    );
  }
},

Run the code and check if it is working or not.

I am running code on my browser so keyboard type won't work.

Here is the result.


So we have successfully made our app.

Conclusion

we have successfully made our app with Form and Text Validation. Hope you liked the tutorial. If you have any doubts, comment below.



Related Posts

See All

The image sharing apps, shopping apps, etc. have image zoom functionality required to see the image in detail. Today, we will learn to implement the same with the help of a widget, InteractiveViewer.

bottom of page