How to create a Login form with auto validation in the flutter

flutter login form with auto validation

In this post, we will learn how to design Login Form with auto validation in Flutter. When we create new application and our application need login page then we easily create login form in flutter but we want some extra security when user log into our application.So in this post we will learn how to create login form with some extra security. Security like username field validation and password field validation.Before user click on login button we will automatically check correct email address and correct password format by using regular expression.So lets get started. If you interested to read more about flutter then go to the flutter official documentation page.

1) main.dart

It is our main.dart file.This file is root of our application.

import 'package:flutter/material.dart';
import 'package:flutterloginform/loginFormwithAutoValidation.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: 'Login Form',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: LoginFormWithAutoValidation(),
    );
  }
}

2)loginForm.dart

import 'package:flutter/material.dart';
import 'package:flutterloginform/validation.dart';

class LoginFormWithAutoValidation extends StatefulWidget {
  @override
  _LoginFormWithAutoValidationState createState() => _LoginFormWithAutoValidationState();
}

class _LoginFormWithAutoValidationState extends State<LoginFormWithAutoValidation> {

  TextStyle style = TextStyle(fontFamily: 'Montserrat', fontSize: 20.0);
  
  TextEditingController _passwordController = new TextEditingController();
  TextEditingController _emailController = new TextEditingController();

  final _formKey = new GlobalKey<FormState>();

  String _email;
  String _password;
 

  bool _autoValidate = false;

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      backgroundColor: Colors.green[400],
      body: Center(
        child: SingleChildScrollView(
          child: Padding(
            padding: const EdgeInsets.all(10.0),
            child: Card(
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(15),
              ),
              color: Color(0xffF3F3F3),
              elevation: 5,
              child: Padding(
                padding: const EdgeInsets.all(20.0),
                child: Form(
                  key: _formKey,
                  autovalidate: _autoValidate,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[

                      Center(
                          child: Text(
                        "Your Logo Here",
                        style: TextStyle(
                          color: Colors.black,
                          fontSize: 25,
                        ),
                      )),
                      SizedBox(height: 25.0),

             // TextFormField for email address

                      TextFormField(
                        keyboardType: TextInputType.emailAddress,
                        autofocus: false,
                        controller: _emailController,
                        validator: validateEmail,
                        onSaved: (value) => _email = value,
                        style: style,
                        decoration: InputDecoration(
                         contentPadding:
                          EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
                          hintText: "Email",
                          border: OutlineInputBorder(
                           borderRadius:BorderRadius.circular(20.0))),
                      ),

                      SizedBox(height: 25.0),

            // TextFormField for email address

                      TextFormField(
                        autofocus: false,
                        controller: _passwordController,
                        validator: validatePassword,
                        onSaved: (value) => _password = value,
                        style: style,
                        decoration: InputDecoration(
                         contentPadding:
                          EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
                         hintText: "Password",
                         border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(20.0))),
                      ),

                      SizedBox(height: 25.0),

                      Divider(color: Colors.black),      // divider

                      SizedBox(height: 20.0),

                      Material(                   // login button
                        elevation: 5.0,
                        borderRadius: BorderRadius.circular(20.0),
                        color: Colors.green,
                        child: MaterialButton(
                          minWidth: MediaQuery.of(context).size.width,
                 padding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
                          onPressed: () {
                            if (_formKey.currentState.validate()) {
                              Navigator.push(context,
                               MaterialPageRoute(builder: (context) {
                                return LoginFormWithAutoValidation();
                              }));
                            } else {
                              setState(() {                    
                             // validation error
                                _autoValidate = true;
                              });
                            }
                          },
                          child: Text("Login",
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                  color: Colors.white,
                                  fontWeight: FontWeight.bold,
                                  fontSize: 20)),
                        ),
                      ),
                      SizedBox(height: 10.0),
                    ],
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

4)validation.dart

I add all validators into separate file validation.dart. I used ReEx expression for Email and Password validation.

String validatePassword(String value) {
  Pattern pattern = r'^(?=.*?[a-z])(?=.*?[0-9]).{8,}$';
  RegExp regex = new RegExp(pattern);
  if (value.length == 0) {
    return "Password is Required";
  } else if (!regex.hasMatch(value))
    return 'Password required: Alphabet, Number & 8 chars';
  else
    return null;
}

String validateEmail(String value) {
  Pattern pattern =
      r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$';
  RegExp regex = new RegExp(pattern);
  if (value.length == 0) {
    return "Email is Required";
  } else if (!regex.hasMatch(value))
    return 'Enter Valid Email';
  else
    return null;
}

5)Output

Here is the output of above example.

Add a Comment

Your email address will not be published. Required fields are marked *