TextFormField Validation || Form Validation 2022

 

Hey Developer !!! 👋



If you are a flutter developer and if you have created an app that requires an authentication page where the user enters his credentials, you would have used a TextFormField widget.


Now, let's say a user has entered his credentials (email, password, etc) and while doing so he accidentally enters an invalid email address ( for eg: " namegmail.com "), there has to be some way to notify the user to enter the correct email address right?


Well yeah, there is something called validator property in the TextFormField widget.


We use it to specify the kind of input that is to be accepted.


The traditional way of doing it is to put an if-else conditional and validate the input.


Ex:import 'package:flutter/material.dart';


void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
theme: ThemeData(),
);
}
}

class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
var _formKey = GlobalKey<FormState>();
var isLoading = false;

void _submit() {
final isValid = _formKey.currentState!.validate();
if (!isValid) {
return;
}
_formKey.currentState!.save();
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Form Validation"),
leading: Icon(Icons.filter_vintage),
),
//body
body: Padding(
padding: const EdgeInsets.all(16.0),
//form
child: Form(
key: _formKey,
child: Column(
children: <Widget>[
Text(
"Form-Validation In Flutter ",
style: TextStyle(fontSize: 24.0, fontWeight: FontWeight.bold),
),
//styling
SizedBox(
height: MediaQuery.of(context).size.width * 0.1,
),

TextFormField(
validator: (value) {
if (value!.isEmpty) {
return "Required";
}
},
decoration: InputDecoration(
label: Text("Name"),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0),
),
),
),

SizedBox(height: 20,),

TextFormField(
decoration: InputDecoration(
labelText: 'E-Mail',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0),
),
),
keyboardType: TextInputType.emailAddress,
onFieldSubmitted: (value) {
//Validator
},
validator: (value) {
if (value!.isEmpty ||
!RegExp(r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9]+\.[a-zA-Z]+")
.hasMatch(value)) {
return 'Enter a valid email!';
}
return null;
},
),
//box styling
SizedBox(height: 20,),
//text input
TextFormField(
decoration: InputDecoration(
labelText: 'Password',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0),
)),
keyboardType: TextInputType.emailAddress,
onFieldSubmitted: (value) {},
obscureText: true,
validator: (val) {
if (val!.isEmpty) {
return "Required";
}
if (val.length < 6) {
return "Password must be atleast 6 characters long";
}
if (val.length > 20) {
return "Password must be less than 20 characters";
}
if (!val.contains(RegExp(r'[0-9]'))) {
return "Password must contain a number";
}
return null;
},
),
SizedBox(
height: MediaQuery.of(context).size.width * 0.1,
),
RaisedButton(
padding: EdgeInsets.symmetric(
vertical: 10.0,
horizontal: 15.0,
),
child: Text(
"Submit",
style: TextStyle(
fontSize: 24.0,
),
),
onPressed: () => _submit(),
)
],
),
),
),
);
}
}

Keys


What is a key? Every flutter widget has a key. These keys are helpful to flutter when the state changes. These keys help keep track of the widgets in the widget tree.

And yes keys are not necessary for stateless widgets because their state never changes and there is nothing to keep track of. Keys in flutter are of two types - LocalKey and GlobalKey.

GlobalKeys are useful when a widget's information is to be accessed somewhere else in the widget tree.


Form

We come across situations where we need to use multiple TextFormFields in our app. Wouldn't it be nice if there was a way to control all those TextFormFields in a single place? That's where Form comes into the picture. With Form, we can control all those fields and their data can be evaluated and validated together in one place.


_formKey is a GlobalKey to control the state of the Form(we will be implementing this later)



Output



 




Comments

Popular posts from this blog

Unlocking the Power of OOP: A Beginner's Guide to Objects, Encapsulation, Inheritance, Abstraction, and Polymorphism

Mastering Hive in Flutter: A Complete Guide for Beginners to Advanced Users

Flutter Drawer – Create a Smooth Navigation Menu