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

Animated Navigation in Flutter

  Introduction By default, Flutter has no animation when navigating from one Screen to another Screen. But in this tutorial, we are going to learn how to animate the Screen Transition.   Introduction By default, Flutter has no animation when navigating from one Screen to another Screen. But in this tutorial, we are going to learn how to animate the Screen Transition. Table of Contents Project Setup Code Result Project Setup Before directly applying to your existing project, practice the code in some example projects. For this tutorial, we are going to name our project screen_animation_tutorial. Open in VSCode or Android Studio. After that, we will make two Screens. The first Screen will be the Starting screen and the next Screen will be the Final Screen. So go ahead and create two dart files under the lib folder. The main.dart file code should look like this Dart import 'package:flutter/material.dart'; import 'package:screen_animation_tutorial/start_screen.dart'; void ...

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

Flutter : Image Picker Tutorial | Pick single image from Gallery

Introduction In this tutorial, we will create an image picker and display the content on the screen . I mage Picker picks a file from the Storage or Camera and stores it in an XFile object. Implementation Install dependency We will first need the image_picker dependency . To install it, add the following dependency to pubspec.yaml file. image_picker: ^0.8.4+3 Then click on Get Packages in your IDE or run the following command on your Terminal / Command Prompt. flutter pub get Example Import the dependency in your dart file. import 'package:image_picker/image_picker.dart' ; Syntax Image picking is a future task . So we need to await the image picking . Here is the syntax. await _picker.pickImage( source : ImageSource.gallery); Here we have provided the source from the gallery . We can also provide the source as a Camera using the following syntax. await _picker.pickImage( source : Ima...