Flutter Form Validation Example

In this article, We are integrating form validation through example. Form Validation is required in all mobile applications for login, register, update profile etc.

In this example, we display and validate different type of form fields. We are using FormBuilder package for this flutter form validation example. FormBuilder widget provides many inbuilt functionalities like date-time picker, Dropdowns, radio buttons, checkboxes, country picker, slider and many more.

 

Add below dependency in pubspec file

flutter_form_builder: ^3.4.1
 
 

Add FormBuilder Widget For Flutter Form Validation

FormBuilder widget provides key parameter. key parameter is used to get current state of form to check all fields of form are valid or not and we can also get values of all fields using value of key parameter.

class MyFormPage extends StatefulWidget {

@override
MyFormPageState createState() => MyFormPageState();

}

class MyFormPageState extends State<MyFormPage> {

final formKey = GlobalKey<FormBuilderState>();

@override
Widget build(BuildContext context) {

return SafeArea(
     child: Scaffold(
          appBar: AppBar(
               title: Text(“Flutter Form Validation Sample”),
          ),
          body: FormBuilder(
               key: formKey,
          ),
     ),
);
}
}

 
 

Add FormBuilder Fields Widgets

FormBuilderTextField widget is used to display text fields for user input. It provides different attributes. validators property is used to add different validators in the form of array. For example if we give required validator then error is shown below the textfield if textfield is empty on form validation check.

Using decoration property we can set icon, hint text, label text etc. keyboard type property is used to show different types of keyboard. We can also set maximum and minimum length and lines.

FormBuilderTextField(
     attribute: “name”,
     validators: [FormBuilderValidators.required()],
     decoration: InputDecoration(
          icon: Icon(Icons.person),
          hintText: “Enter your name”,
          labelText: “Name”
     ),
),
 
FormBuilderTextField(
     attribute: “email”,
     validators: [FormBuilderValidators.required(), FormBuilderValidators.email()],
     keyboardType: TextInputType.emailAddress,
     decoration: InputDecoration(
          icon: Icon(Icons.email),
          hintText: “Enter your email”,
          labelText: “Email”
     ),
),
 
FormBuilderTextField(
     attribute: “mobile”,
     validators: [FormBuilderValidators.required(), FormBuilderValidators.numeric()],
     decoration: InputDecoration(
          icon: Icon(Icons.phone),
          hintText: “Enter your mobile no”,
          labelText: “Mobile No”
     ),
),
 
FormBuilderTextField(
     attribute: “age”,
     decoration: InputDecoration(labelText: “Age”),
     keyboardType: TextInputType.number,
     maxLength: 3,
     validators: [
          FormBuilderValidators.numeric(),
          FormBuilderValidators.max(70),
     ],
),
 
FormBuilderTextField(
     attribute: “password”,
     decoration: InputDecoration(labelText: “Password”),
     obscureText: true,
     maxLines: 1,
     maxLength: 16,
     validators: [
          FormBuilderValidators.required(),
          FormBuilderValidators.minLength(8),
          FormBuilderValidators.maxLength(16)
     ],
),
 

FormBuilderDateTimePicker widget is used to display date and time pickers. This widget provides inputType property which is used to display datepicker or timepicker or both.

FormBuilderDateTimePicker(
     attribute: “date”,
     inputType: InputType.date,
     format: DateFormat(“dd-MM-yyyy”),
     decoration: InputDecoration(labelText: “Date of Birth”),
     validators: [FormBuilderValidators.required()],
),
 

We can also display radio buttons and check boxes in flutter form with the help of FormBuilderRadioGroup and FormBuilderCheckboxList. These widgets are used to display group of options. Using initialValue parameter we can display initial value on form launch.

FormBuilderRadioGroup(
     attribute: “gender”,
     decoration: InputDecoration(
          labelText: “Gender”,
          labelStyle: TextStyle(fontWeight: FontWeight.bold, fontSize: 22)
     ),
     options: [
          FormBuilderFieldOption(value: “Male”),
          FormBuilderFieldOption(value: “Female”),
          FormBuilderFieldOption(value: “Custom”),
     ],
),
 
FormBuilderCheckboxList(
     attribute: “languages”,
     initialValue: [“English”],
     decoration: InputDecoration(
          labelText: “Languages You Speak”,
          labelStyle: TextStyle(fontWeight: FontWeight.bold, fontSize: 22)
     ),
     options: [
          FormBuilderFieldOption(value: “English”),
          FormBuilderFieldOption(value: “Spanish”),
          FormBuilderFieldOption(value: “French”),
     ],
),
 

FlutterFormBuilder widget also provides country picker functionality. FormBuilderCountryPicker widget display all countries with flags in dropdown. So user can select any single country.

FormBuilderCountryPicker(
     attribute: “country”,
     initialValue: “United States”,
     decoration: InputDecoration(
          labelText: “Country”,
          labelStyle: TextStyle(fontWeight: FontWeight.bold, fontSize: 22)
     ),
),
 
 

Final Code

 
import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:intl/intl.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Form Validation Sample',
      home: MyFormPage(),
    );
  }
}

class MyFormPage extends StatefulWidget {

  @override
  MyFormPageState createState() => MyFormPageState();

}

class MyFormPageState extends State<MyFormPage> {

  final formKey = GlobalKey<FormBuilderState>();

  @override
  Widget build(BuildContext context) {

    return SafeArea(
      child: Scaffold(
        appBar: AppBar(
          title: Text("Flutter Form Validation Sample"),
        ),
        body: FormBuilder(
          key: formKey,
          child: SingleChildScrollView(
            child: Container(
              padding: EdgeInsets.all(15),
              child: Column(
                children: <Widget>[
                  FormBuilderTextField(
                    attribute: "name",
                    validators: [FormBuilderValidators.required()],
                    decoration: InputDecoration(
                        icon: Icon(Icons.person),
                        hintText: "Enter your name",
                        labelText: "Name"
                    ),
                  ),
                  SizedBox(height: 25),
                  FormBuilderTextField(
                    attribute: "email",
                    validators: [FormBuilderValidators.required(), FormBuilderValidators.email()],
                    keyboardType: TextInputType.emailAddress,
                    decoration: InputDecoration(
                        icon: Icon(Icons.email),
                        hintText: "Enter your email",
                        labelText: "Email"
                    ),
                  ),
                  SizedBox(height: 25),
                  FormBuilderTextField(
                    attribute: "mobile",
                    validators: [FormBuilderValidators.required(), FormBuilderValidators.numeric()],
                    decoration: InputDecoration(
                        icon: Icon(Icons.phone),
                        hintText: "Enter your mobile no",
                        labelText: "Mobile No"
                    ),
                  ),
                  SizedBox(height: 25),
                  FormBuilderDateTimePicker(
                    attribute: "date",
                    inputType: InputType.date,
                    format: DateFormat("dd-MM-yyyy"),
                    decoration: InputDecoration(labelText: "Date of Birth"),
                    validators: [FormBuilderValidators.required()],
                  ),
                  SizedBox(height: 25),
                  FormBuilderTextField(
                    attribute: "age",
                    decoration: InputDecoration(labelText: "Age"),
                    keyboardType: TextInputType.number,
                    maxLength: 3,
                    validators: [
                      FormBuilderValidators.numeric(),
                      FormBuilderValidators.max(70),
                    ],
                  ),
                  SizedBox(height: 25),
                  FormBuilderRadioGroup(
                    attribute: "gender",
                    decoration: InputDecoration(
                      labelText: "Gender",
                      labelStyle: TextStyle(fontWeight: FontWeight.bold, fontSize: 22)
                    ),
                    options: [
                      FormBuilderFieldOption(value: "Male"),
                      FormBuilderFieldOption(value: "Female"),
                      FormBuilderFieldOption(value: "Custom"),
                    ],
                  ),
                  SizedBox(height: 25),
                  FormBuilderCheckboxList(
                    attribute: "languages",
                    initialValue: ["English"],
                    decoration: InputDecoration(
                        labelText: "Languages You Speak",
                        labelStyle: TextStyle(fontWeight: FontWeight.bold, fontSize: 22)
                    ),
                    options: [
                      FormBuilderFieldOption(value: "English"),
                      FormBuilderFieldOption(value: "Spanish"),
                      FormBuilderFieldOption(value: "French"),
                    ],
                  ),
                  SizedBox(height: 25),
                  FormBuilderCountryPicker(
                    attribute: "country",
                    initialValue: "United States",
                    decoration: InputDecoration(
                        labelText: "Country",
                        labelStyle: TextStyle(fontWeight: FontWeight.bold, fontSize: 22)
                    ),
                  ),
                  SizedBox(height: 25),
                  FormBuilderTextField(
                    attribute: "password",
                    decoration: InputDecoration(labelText: "Password"),
                    obscureText: true,
                    maxLines: 1,
                    maxLength: 16,
                    validators: [
                      FormBuilderValidators.required(),
                      FormBuilderValidators.minLength(8),
                      FormBuilderValidators.maxLength(16)],
                  ),
                  SizedBox(height: 40),
                  RaisedButton(
                    child: Text("Submit"),
                    onPressed: (){
                      formKey.currentState.save();
                      if(formKey.currentState.validate()){
                        print(formKey.currentState.value);
                      }
                    },
                  ),
                  SizedBox(height: 30),
                ],
              ),
            ),
          )
        ),
      ),
    );
  }
}

 
 
 
 
Flutter Form Validation
 
Flutter Form Validation
 
 
 

Leave a Reply