Form Validation in Flutter explained

Form Validation in Flutter explained


Flutter Form Validation makes applications safe and easy to use, making sure that the user’s information is valid.

In this article, we will learn how to validate forms in Flutter applications.

For illustration, consider the following simple app.

Before We Kick Off

First we need to make sure:

  • You have a text editor ( VsCode ).
  • You have Flutter running on your computer.
  • You have basic knowledge of Flutter and Dart language.
  • Create a Flutter project named VALIDATE_FORM.

Create a Form with a GlobalKey

On lib folder create form_validation.dart file. Start with this code:

import 'package:flutter/material.dart';

class FormValidation extends StatefulWidget {
  @override
  _FormValidationState createState() => _FormValidationState();
}

class _FormValidationState extends State<FormValidation> {
  String _name;
  String _email;
  String _password;
  String _phone;
  String _url;
  String _weight;

  final GlobalKey<FormState> _formKey  = GlobalKey<FormState>();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Form Validation Demo")
      ),
       body: SingleChildScrollView(
         child: Container(
           margin: EdgeInsets.all(16),
           child: Form(
             key: _formKey,
             child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  // all the fields
                ]
             )
             ),
         ),
       ),
    );
  }
}

Above we have:

  • Variables.
  • A GlobalKey _formKey that is the standard way to use forms in Flutter and it is used for identify the form. You can go deeper about GlobalKey using the official documentation.

Add fields with basic validation logic

To add the fields we’ll use the TextFormField widget because it renders a material design text field and can display validation errors when they occur.

Firstly, we’ll start with _name, create a widget that returns a TextFormField. In the code bellow we set the max length of the input. You can see that if the user’s input isn’t valid (empty for our example), the validator function returns a String containing an error message. Then we save the entered value.

  Widget _buildName(){
    return TextFormField(
      maxLength: 15,
      keyboardType: TextInputType.text,
      decoration: InputDecoration(
        labelText: 'Name',
      ),
      validator: (String value) {
        if(value.isEmpty){
          return 'Name is required.';
        }
      },
      onSaved: (String value){
        _name = value;
      },
    );
  }

Do the same for _email . But in addition to that you can use RegEx to validate the string. RegEx is a string of text that allows you to create patterns that help match, locate, and manage text.

    Widget _buildEmail(){
    return TextFormField(
      decoration: InputDecoration(
        labelText: 'Email'
      ),
      validator: (String value) {
        if(value.isEmpty){
          return 'Email is required';
        }

        if(!RegExp("^[a-zA-Z0-9.!#%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,253}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,253}[a-zA-Z0-9])?)*").hasMatch(value)){
          return 'Enter a valid email address';
        }

        // validator has to return something :)
        return null;

      },
      onSaved: (String value) {
        _email = value;
      },
    );
  }

For _password. The password field will be visible.

    Widget _buildPassword(){
    return TextFormField(
      decoration: InputDecoration(
        labelText: 'Paswword'
      ),
      keyboardType: TextInputType.visiblePassword,
      validator: (String value) {
        if(value.isEmpty){
          return 'Password is required';
        }
      },
      onSaved: (String value){
        _password = value;
      },
    );
  }

For _phone we set the keyboardType to number and we check the input that is empty or not. Then we save the input in the variable.

    Widget _buildPhone(){
    return TextFormField(
      decoration: InputDecoration(
        labelText: 'Phone number'
      ),
      keyboardType: TextInputType.phone,
      validator: (String value) {
        if(value.isEmpty){
          return 'Phone number is required';
        }
      },
      onSaved: (String value){
        _phone = value;
      },
    );
  }

The same for _url. We just need to set the keyboardType to URL.

    Widget _buildUrl(){
    return TextFormField(
      decoration: InputDecoration(
        labelText: 'URL'
      ),
      keyboardType: TextInputType.url,
      validator: (String value) {
        if(value.isEmpty){
          return 'URL is required';
        }
      },
      onSaved: (String value){
        _url = value;
      },
    );
  }

For _age we parse to an int value and check that the value is greater then zero.

    Widget _buildAge(){
    return TextFormField(
      decoration: InputDecoration(
        labelText: 'Age'
      ),
      keyboardType: TextInputType.number,
      validator: (String value) {

        int age = int.tryParse(value);
        if(age == null || age <= 0){
          return 'Age must be greater then 0';
        }
      },
      onSaved: (String value){
        _age = value;
      },
    );
  }

After that, we need to add the fields that we created in our children widget we need to add the fields .

_buildName(),
_buildEmail(),
_buildPassword(),
_buildPhone(),
_buildUrl(),
_buildAge(),

Create a Button to Submit and Validate the Form

Now we need to provide a button that the user can tap to submit the information.

When the user attempts to submit the form, we’ll check if the form is valid and to do so we use the _formKey. If it is, we’ll save the form and print the values on the console, but if it isn’t we’ll just display the error message.

RaisedButton(
   child: Text('Save',
            style: TextStyle(
                 color:Colors.blue,
                    fontSize: 16
                    ),
               ),
      onPressed: () {
            if(!_formKey.currentState.validate()) {
                    return;
             }
            _formKey.currentState.save();
             print(_name);
             print(_email);
             print(_password);
             print(_phone);
             print(_url);
             print(_age);
                    }
                  )

Call this class in your main.dart file and run it!

Conclusion

You learned the very basic form validation in Flutter, and now you are ready to go further. You can find here the full code.

Thanks for reading!


Share on social media

//