Open In App

Flutter – Handle TextField Validation in Password

Last Updated : 14 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads