Skip to main content

Form and Text Validation in Flutter

Introduction

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.
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.

If you want a full tutorial on TextFormField, click here.

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.

App UI


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.

Final App

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.



Comments

Popular posts from this blog

Flutter | Material Banner Tutorial

In this tutorial, we will create and display Material Banner in Flutter . Material Banners are displayed at the top of the screen . User interaction is required to dismiss the banner . Material Banner Material Banner alerts the user about action and p rovides some actions for the user to take . In brief, it alerts the user about an issue and the user address the issue . The user should dismiss the banner to remove it from the screen else it will be active. Syntax  ScaffoldMessenger.of(context).showMaterialBanner(MaterialBanner( content: content, actions: actions)) Code Here is our starting class. It is a stateless class and we will display a banner when the Button is pressed. class SnackBarTutorial extends StatelessWidget { const SnackBarTutorial({Key ? key}) : super ( key: key); @ override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text( "Material Banner"

How to create Snackbars in Flutter | Snackbar Tutorial

In this article, we will create and display different types of SnackBars in Flutter.  SnackBars in Flutter SnackBars are used to briefly display some information or inform the user about an action. For instance, when a user deletes a mail or message you may want to inform the user about the action. Also, the user can undo the action he performed by the undo button in the Snackbar . Syntax For creating a SnackBar, we use the following code. ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: content)); Inside the content field of SnackBar, we will pass the content. Any content can be passed inside it, but in practice, small messages with or without a button. Example Simple SnackBar class SnackBarTutorial extends StatelessWidget {   const SnackBarTutorial({Key? key}) : super (key: key);   @override   Widget build(BuildContext context) {     return

Flutter: DatePicker Tutorial both with Material and Cupertino Style

Introduction DatePicker is very important when you want the user to pick his / her date of birth or something else. In Flutter, implementing DatePicker is very easy and we will implement DatePicker in both Android or Material style and Cupertino or IOS style.  Table of contents Approach Project Setup Material Style DatePicker Cupertino Style DatePicker Conclusion Approach Flutter has widgets for everything and even for DatePicker. DatePicker widget is loaded with all needed animation and colours. So implementation is very easy.  Project Setup No extra plugins are required for this project and you can continue with your existing project. Here is the starting code. class DatePickerTutorial extends StatefulWidget { const DatePickerTutorial({Key? key}) : super (key: key); @ override _DatePickerTutorialState createState() => _DatePickerTutorialState(); } class _DatePickerTutorialState extends State<DatePick