flutter form validation email and password confirm
flutter form validation email and password confirm

Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial we will check how to create forms in flutter with validation such as empty TextField, Email Validation, and password and confirm password validation in flutter

So let’s begin

Steps for form validation

  1. Create Form with a GlobalKey<FormState>.
  2. Add some TextFormField with validation that required.
  3. Create a button where you check for flutter form validation and submit it.

Step 1: Form Creation and assigning it a GlobalKey with FormState

First make use of Form Widget, This will work as a group & help you in managing validating multiple flutter forms textfield easily.
Then, after creating a form in flutter, provide it with GlobalKey<FormState>, It will help you  in allowing validation to form in proper order & very easily.

As show in below Snippet flutter code

final _formKey = GlobalKey<FormState>();

@override
  Widget build(BuildContext context) {
    // Build a Form widget using the _formKey created above.
    return Form(
      key: _formKey,    
      child: Column(
        children: <Widget>[
              // Add TextFormFields and RaisedButton here.
        ]
     )
    );
  }

Here i have created a globalkey as formState then in widget Tree, I have made use of Form Widget and assigned key: as _formKey, and form has child as Column so that we can create TextFormField for Flutter Form Validation.

Step 2: Adding TextFormField with Validation email, password confirm

TextFormField widget comes from Material design & it can also display validation error, whenever any user do not fullfill TextFormField Requirement,
This we can do by applying Validation Rules to particular flutter Textfield by providing validation properties rules to it.

If user enter any invalid input, then Validator function in flutter will detect it & return a appropriate error message at the bottom of TextField.

TextFormField(
  // The validator receives the text that the user has entered.
  validator: (value) {
    if (value.isEmpty) {
      return 'Please enter some text';
    }
    return null;
  },
);

If user submit the form without any data then validator will take care by showing proper text message to user, as shown in below screenshot.

flutter form validation using global formstate

Step 3: OnButton Pressed Check for Form Validation

So, Now as you have designed flutter form with TextFormField with validation, now simple create a button(should be inside the Form Widget tag), using which the user can submit the form filled with information in it.

When a user attempt to submit the form onPressed, we will check if flutetr form field by user is as per required validation, Then if the form is valid then send all the data info to database server to be saved, else if the form is invalidthen show a proper error message to the user under the flutter textfield where validation is not authorized.

RaisedButton(
  onPressed: () {
    // Validate returns true if the form is valid, otherwise false.
    if (_formKey.currentState.validate()) {
      // If the form is valid, display a snackbar. In the real world,
      // you'd often call a server or save the information in a database.

      Scaffold
          .of(context)
          .showSnackBar(SnackBar(content: Text('Processing Data')));
    }
  },
  child: Text('Submit'),
);

We are using GlobalKey formState under Form so, Form Validation will automatically detect where uses validation has failed.

Video Tutorial

Complete Source Code of Form Validation in Flutter

UI Design

flutter form validation email confirm password

Project Structure

Here InputDeco_design.dart file is an decoration of TextFormField, As you can see in UI design TextField has border and radius.

Source Codes


main.dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_form_validator/FormPage.dart';
import 'package:flutter_form_validator/InputDeco_design.dart';
void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: FormPage(),
    );
  }
}



InputDeco_design.dart

import 'package:flutter/material.dart';

  InputDecoration buildInputDecoration(IconData icons,String hinttext) {
  return InputDecoration(
    hintText: hinttext,
    prefixIcon: Icon(icons),
    focusedBorder: OutlineInputBorder(
      borderRadius: BorderRadius.circular(25.0),
      borderSide: BorderSide(
          color: Colors.green,
          width: 1.5
      ),
    ),
    border: OutlineInputBorder(
      borderRadius: BorderRadius.circular(25.0),
      borderSide: BorderSide(
        color: Colors.blue,
        width: 1.5,
      ),
    ),
    enabledBorder:OutlineInputBorder(
      borderRadius: BorderRadius.circular(25.0),
      borderSide: BorderSide(
        color: Colors.blue,
        width: 1.5,
      ),
    ),
  );
}

FormPage.dart

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

class FormPage extends StatefulWidget {
  @override
  _FormPageState createState() => _FormPageState();
}

class _FormPageState extends State<FormPage> {

  String name,email,phone;

  //TextController to read text entered in text field
  TextEditingController password = TextEditingController();
  TextEditingController confirmpassword = TextEditingController();

  final GlobalKey<FormState> _formkey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: SingleChildScrollView(
          child: Form(
            key: _formkey,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                CircleAvatar(
                  radius: 70,
                  child: Image.network("https://protocoderspoint.com/wp-content/uploads/2020/10/PROTO-CODERS-POINT-LOGO-water-mark-.png"),
                ),
                SizedBox(
                  height: 15,
                ),
                Padding(
                  padding: const EdgeInsets.only(bottom:15,left: 10,right: 10),
                  child: TextFormField(
                    keyboardType: TextInputType.text,
                    decoration: buildInputDecoration(Icons.person,"Full Name"),
                    validator: (String value){
                      if(value.isEmpty)
                      {
                        return 'Please Enter Name';
                      }
                      return null;
                    },
                    onSaved: (String value){
                      name = value;
                    },
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(bottom: 15,left: 10,right: 10),
                  child: TextFormField(
                    keyboardType: TextInputType.text,
                    decoration:buildInputDecoration(Icons.email,"Email"),
                    validator: (String value){
                      if(value.isEmpty)
                      {
                        return 'Please a Enter';
                      }
                      if(!RegExp("^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+.[a-z]").hasMatch(value)){
                        return 'Please a valid Email';
                      }
                      return null;
                    },
                    onSaved: (String value){
                      email = value;
                    },
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(bottom: 15,left: 10,right: 10),
                  child: TextFormField(
                    keyboardType: TextInputType.number,
                    decoration:buildInputDecoration(Icons.phone,"Phone No"),
                    validator: (String value){
                      if(value.isEmpty)
                      {
                        return 'Please enter phone no ';
                      }
                      return null;
                    },
                    onSaved: (String value){
                      phone = value;
                    },
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(bottom: 15,left: 10,right: 10),
                  child: TextFormField(
                    controller: password,
                    keyboardType: TextInputType.text,
                    decoration:buildInputDecoration(Icons.lock,"Password"),
                    validator: (String value){
                      if(value.isEmpty)
                      {
                        return 'Please a Enter Password';
                      }
                      return null;
                    },

                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(bottom: 15,left: 10,right: 10),
                  child: TextFormField(
                    controller: confirmpassword,
                    obscureText: true,
                    keyboardType: TextInputType.text,
                    decoration:buildInputDecoration(Icons.lock,"Confirm Password"),
                    validator: (String value){
                      if(value.isEmpty)
                      {
                        return 'Please re-enter password';
                      }
                      print(password.text);

                      print(confirmpassword.text);

                      if(password.text!=confirmpassword.text){
                        return "Password does not match";
                      }

                      return null;
                    },

                  ),
                ),

                SizedBox(
                  width: 200,
                  height: 50,
                  child: RaisedButton(
                    color: Colors.redAccent,
                    onPressed: (){

                      if(_formkey.currentState.validate())
                      {
                        print("successful");

                        return;
                      }else{
                        print("UnSuccessfull");
                      }
                    },
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(50.0),
                        side: BorderSide(color: Colors.blue,width: 2)
                    ),
                    textColor:Colors.white,child: Text("Submit"),

                  ),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
}

Output

Flutter Form Email Validation

flutter validation email

Flutter form confirm password –
password and confirm password validation must match

flutter password validation and confirm password validation must match

Download Source Code from GitHub  Link: https://github.com/RajatPalankar8/flutter_form_validation.git 

Recommended Articles

flutter email validation

password validation regex – Android