Forms and Validation in Flutter — Login UI

Yogita Kumar
The Startup

--

Let’s see how to design login form and validate it in flutter.

To get a form in our Scaffold widget, we have to use Form widget

@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: Text("Login Page"),
),
body: SingleChildScrollView(
child: Form()
),
);
}

This will return nothing rather than the error messages. Form widget here is just a container for form.

To implement validation using Form() , we need global key that is going to tell us about any change in Form() widget.

For that just declare,
GlobalKey formkey = GlobalKey();
but since it is related to Form state so explicitly mention <FormState>

GlobalKey<FormState> formkey = GlobalKey<FormState>();

Now mention that formkey is the key for this particular Form,
set key property to formkey. This GlobalKey uniquely identifies this Form.

TextFormField is a widget to take input from user. This is just similar to TextField widget. TextFormField is also decorated in same way as TextField.

TextFormField(
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Password',
hintText: 'Enter secure password'),
),

Now if we want to add some validation then in TextFormField set property validator as follows:
This validator takes the present value of widget, means here what is inside TextFormField.

validator: (value) {
if (value.isEmpty) {
return "* Required";
} else
return null;
},

If there is no text entered it will give message “* Required” otherwise returns null.

If want to validate text field with different condition then simply use,

validator: (value) {
if (value.isEmpty) {
return "* Required";
} else if (value.length < 6) {
return "Password should be atleast 6 characters";
} else if (value.length > 15) {
return "Password should not be greater than 15 characters";
} else
return null;
},

Lets make different function name as validatePassword() for this TextFormFeild’s validation.

String validatePassword(String value) {
if (value.isEmpty) {
return "* Required";
} else if (value.length < 6) {
return "Password should be atleast 6 characters";
} else if (value.length > 15) {
return "Password should not be greater than 15 characters";
} else
return null;
}

call this function in password TextFormField as:

validator: validatePassword,

It take value as a parameter but we don’t need to provide it here.

To call this validation, on Login Buttons’s onPressed() event write code for current state of form is validate or not.

 onPressed:(){
if (_formKey.currentState.validate()) {
print("Validated");
}else{
print("Not Validated");
}
}

There is one more property of form is autovalidate :

autovalidate: true,

If value of autovalidate is true it will check for validation while typing, if it is false then it will show validation in onPressed() event of Login button, By default it has false value.

Flutter has form_field_validator package for form validation, lets see how to use that in this application.

in pubspec.yaml file add

dependencies:
flutter:
sdk: flutter
form_field_validator: ^1.0.1

click on Packages get-> we get exit code 0 message

to use this package import file

import 'package:form_field_validator/form_field_validator.dart';

Now for email field, check valid email address, then by using form_field_validator package, set validator property of Email TextFormField as

validator:EmailValidator(errorText: "Enter valid email id"),

errorText is a message that will be displayed as a result of validation to TextFormField.

It will show you error message until user not providing proper email address.

And if want to apply more than one validation then use Multivalidator. Multivalidor takes a list of validators, as :

validator: MultiValidator([
RequiredValidator(errorText: "* Required"),
EmailValidator(errorText: "Enter valid email id"),
])

Use Multivalidator for Password TextFormField as :

MultiValidator([
RequiredValidator(errorText: "* Required"),
MinLengthValidator(6,errorText: "Password should be atleast 6 characters"),
MaxLengthValidator(15,errorText: "Password should not be greater than 15 characters")
])

MinLengthValidator and MaxLengthValidator take first argument as a minimum length and maximum length resp. against which we have to do validation, errorText is a message to print as a result of validation.

TestFormField for Email and password :

Padding(
padding: EdgeInsets.symmetric(horizontal: 15),
child: TextFormField(
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Email',
hintText: 'Enter valid email id as abc@gmail.com'),
validator: MultiValidator([
RequiredValidator(errorText: "* Required"),
EmailValidator(errorText: "Enter valid email id"),
])),
),
Padding(
padding: const EdgeInsets.only(
left: 15.0, right: 15.0, top: 15, bottom: 0),
child: TextFormField(
obscureText: true,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Password',
hintText: 'Enter secure password'),
validator: MultiValidator([
RequiredValidator(errorText: "* Required"),
MinLengthValidator(6,
errorText: "Password should be atleast 6 characters"),
MaxLengthValidator(15,
errorText:
"Password should not be greater than 15 characters")
])
//validatePassword, //Function to check validation
),
),

Find full source code on

Thank you!

--

--

Yogita Kumar
The Startup

Google Developer Expert Flutter| Cloud Enthusiast | Full Stack Developer | .NET Developer |Coach and Trainer