Flutter - Handle TextField Validation in Password
Last Updated :
24 Apr, 2025
Password validation is a method to validate whether the given password entered by the user meets some specific condition or not according to it if the password satisfies the given condition then the password is valid otherwise the password is invalid. In this article we are going to create a password validation application in Flutter that will validate the password with some conditions like :
- Password length must be greater than 6
- Contains at least one uppercase letter
- Contains at least one lowercase letter
- Contains at least one digit (0-9)
- Contains at least one special character
A sample video is given below to get an idea about what we are going to do in this article.
Step By Step Implementation
Step 1: Create a New Project in Android Studio
To set up Flutter Development on Android Studio please refer to Android Studio Setup for Flutter Development, and then create a new project in Android Studio please refer to Creating a Simple Application in Flutter.
Step 2: Import the Package
First of all import material.dart file.
import 'package:flutter/material.dart';
Step 3: Execute the main Method
Here the execution of our app starts.
Dart
void main() {
runApp(MyApp());
}
Step 4: Create MyApp Class
In this class we are going to implement the MaterialApp , here we are also set the Theme of our App.
Dart
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
// Set the app's primary theme color
primarySwatch: Colors.green,
),
debugShowCheckedModeBanner: false,
home: PasswordValidator(),
);
}
}
Step 5: Create PasswordValidator Class
This class contains a boolean method named as _validatePassword function is responsible for checking the entered password against a set of criteria. It checks whether the password length is greater than 6, contains at least one uppercase letter, one lowercase letter, one digit, and one special character. If any of these criteria are not met, an error message is accumulated in the _errorMessage string. Comments are added for better understanding of the code.
// Function to validate the password
bool _validatePassword(String password) {
// Reset error message
_errorMessage = '';
// Password length greater than 6
if (password.length <6) {
_errorMessage += 'Password must be longer than 6 characters.\n';
}
// Contains at least one uppercase letter
if (!password.contains(RegExp(r'[A-Z]'))) {
_errorMessage += '• Uppercase letter is missing.\n';
}
// Contains at least one lowercase letter
if (!password.contains(RegExp(r'[a-z]'))) {
_errorMessage += '• Lowercase letter is missing.\n';
}
// Contains at least one digit
if (!password.contains(RegExp(r'[0-9]'))) {
_errorMessage += '• Digit is missing.\n';
}
// Contains at least one special character
if (!password.contains(RegExp(r'[!@#%^&*(),.?":{}|<>]'))) {
_errorMessage += '• Special character is missing.\n';
}
// If there are no error messages, the password is valid
return _errorMessage.isEmpty;
}
Dart
class PasswordValidator extends StatefulWidget {
@override
_PasswordValidatorState createState() => _PasswordValidatorState();
}
class _PasswordValidatorState extends State<PasswordValidator> {
TextEditingController _passwordController = TextEditingController();
bool _isValid = false;
String _errorMessage = '';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Password Validator'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// Text field to input the password
TextField(
controller: _passwordController,
obscureText: true,
decoration: InputDecoration(
labelText: 'Enter Password',
),
),
SizedBox(height: 20),
// Button to trigger password validation
ElevatedButton(
onPressed: () {
setState(() {
_isValid = _validatePassword(_passwordController.text);
});
},
child: Text('Validate Password'),
),
SizedBox(height: 20),
// Display the result of password validation
_isValid
? Text(
'Password is valid!',
style: TextStyle(color: Colors.green),
)
: Text(
'Password is not valid!\n'
'• $_errorMessage',
style: TextStyle(color: Colors.red),
),
],
),
),
);
}
// Function to validate the password
bool _validatePassword(String password) {
// Reset error message
_errorMessage = '';
// Password length greater than 6
if (password.length <6) {
_errorMessage += 'Password must be longer than 6 characters.\n';
}
// Contains at least one uppercase letter
if (!password.contains(RegExp(r'[A-Z]'))) {
_errorMessage += '• Uppercase letter is missing.\n';
}
// Contains at least one lowercase letter
if (!password.contains(RegExp(r'[a-z]'))) {
_errorMessage += '• Lowercase letter is missing.\n';
}
// Contains at least one digit
if (!password.contains(RegExp(r'[0-9]'))) {
_errorMessage += '• Digit is missing.\n';
}
// Contains at least one special character
if (!password.contains(RegExp(r'[!@#%^&*(),.?":{}|<>]'))) {
_errorMessage += '• Special character is missing.\n';
}
// If there are no error messages, the password is valid
return _errorMessage.isEmpty;
}
}
Here is the full Code of main.dart file
Dart
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.green, // Set the app's primary theme color
),
debugShowCheckedModeBanner: false,
home: PasswordValidator(),
);
}
}
class PasswordValidator extends StatefulWidget {
@override
_PasswordValidatorState createState() => _PasswordValidatorState();
}
class _PasswordValidatorState extends State<PasswordValidator> {
TextEditingController _passwordController = TextEditingController();
bool _isValid = false;
String _errorMessage = '';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Password Validator'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// Text field to input the password
TextField(
controller: _passwordController,
obscureText: true,
decoration: InputDecoration(
labelText: 'Enter Password',
),
),
SizedBox(height: 20),
// Button to trigger password validation
ElevatedButton(
onPressed: () {
setState(() {
_isValid = _validatePassword(_passwordController.text);
});
},
child: Text('Validate Password'),
),
SizedBox(height: 20),
// Display the result of password validation
_isValid
? Text(
'Password is valid!',
style: TextStyle(color: Colors.green),
)
: Text(
'Password is not valid!\n'
'• $_errorMessage',
style: TextStyle(color: Colors.red),
),
],
),
),
);
}
// Function to validate the password
bool _validatePassword(String password) {
// Reset error message
_errorMessage = '';
// Password length greater than 6
if (password.length <6) {
_errorMessage += 'Password must be longer than 6 characters.\n';
}
// Contains at least one uppercase letter
if (!password.contains(RegExp(r'[A-Z]'))) {
_errorMessage += '• Uppercase letter is missing.\n';
}
// Contains at least one lowercase letter
if (!password.contains(RegExp(r'[a-z]'))) {
_errorMessage += '• Lowercase letter is missing.\n';
}
// Contains at least one digit
if (!password.contains(RegExp(r'[0-9]'))) {
_errorMessage += '• Digit is missing.\n';
}
// Contains at least one special character
if (!password.contains(RegExp(r'[!@#%^&*(),.?":{}|<>]'))) {
_errorMessage += '• Special character is missing.\n';
}
// If there are no error messages, the password is valid
return _errorMessage.isEmpty;
}
}
Output:
Similar Reads
Flutter - Show/Hide Password in TextField
In this article, we will Implement how to show/hide the password in the Textfield. A sample video is given below to get an idea about what we are going to do in this article. Step by Step Implementation Step 1: Create a New Project in Android Studio To set up Flutter Development on Android Studio pl
3 min read
Flutter - Textfield Validation
If you are building the sign-in or sign-up page in Android application, then Obviously you need to validate the Text field. otherwise, it can be null or empty. This will cause save the null values into the database. Then further make the application less impact. So to overcome this problem we need t
3 min read
Form Validation in Flutter
Form Validation is an important part of every application. In the flutter application, there are many ways to validate form such as using a TextEditingController. But handling text controller for every Input can be messy in big applications. Hence, Form provides us a convenient way to validate user
3 min read
Flutter - Phone Number Validator
In Flutter, Validating phone numbers is a crucial step to ensure data accuracy and enhance user experience. Flutter, provides a powerful package for handling phone number input and validation with the intl_phone_number_input package. In this article, we'll explore how to streamline phone number vali
6 min read
Flutter - Gradient TextFields
Decorating text fields can be a big task if you have a large application. There is a package gradient_textfield that could make this time-consuming task pretty simple and fast. Although in Flutter we can create text fields using TextField, for beginners especially, it takes time to understand decora
3 min read
Flutter - Generate Strong Random Password
In this article, we are going to make an application in Flutter that generates random passwords that cannot be easily cracked by hackers or attackers. Here we define a method named _generatePassword that is responsible for generating random passwords. It uses a mix of lowercase letters, uppercase le
4 min read
Retrieve the Value of the TextField in Flutter
The text field is widely used in Android Applications for taking user input, using TextEditingController we can retrieve the data from the text field. A sample video gives you an idea of what we are going to do in this article. Step By Step ImplementationStep 1: Create a New Project in Android Studi
2 min read
Flutter - Make a Toggle Password Visibility Button
In this article, we are going to create a button when pressed, displays the password entered in the obscured text field in Flutter. In this we are going to take a boolean variable named as showPassword, If showPassword is true, the password is displayed in plain text, otherwise, it is obscured. In t
4 min read
Multiline TextField in Flutter
Multiline TextField is the input TextField which takes the input in more than one line, This type of TextField is used in the scenario like taking Feedback from the user, User Comments, and Description, etc., We can achieve multiline TextField by setting the property keyBoardType and maxLines of the
2 min read
Flutter - String Validator
If you are a developer and making applications and websites then you must have to validate different things whether it is email, URL, Credit Card Number, divisibility, and many more. If you get the same issue in Flutter to write different functions for validation then now you can use this package in
2 min read