Image for post
Image for post

Forms and Validation in Flutter — Login UI

Yogita Kumar
Nov 26, 2020 · 4 min read

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.

Image for post
Image for post

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!

The Startup

Medium's largest active publication, followed by +754K people. Follow to join our community.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store