Skip to content

Instantly share code, notes, and snippets.

@BarryDaBee
Last active March 2, 2023 13:04
Show Gist options
  • Save BarryDaBee/327d15550334ff10853a875fd8159c2e to your computer and use it in GitHub Desktop.
Save BarryDaBee/327d15550334ff10853a875fd8159c2e to your computer and use it in GitHub Desktop.
A simple widget for validating password conditions like length >= 8, hasNumber etc
import 'package:flutter/material.dart';
const Color darkBlue = Color.fromARGB(255, 18, 32, 47);
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final _passwordController = TextEditingController();
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(
scaffoldBackgroundColor: darkBlue,
),
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Column(
children: [
TextField(
controller: _passwordController,
),
ValueListenableBuilder(
valueListenable: _passwordController,
builder: (context, textEditingValue, _) {
final password = textEditingValue.text;
final hasAtLeastEightChars = password.length >= 8;
final hasUpperAndLowerCaseChars = password.contains(RegExp('[A-Z]'));
final hasNumber = password.contains(RegExp('[0-9]'));
final hasSpecialChar = password.contains(RegExp(r'[!@#$%^&*(),.?":{}|<>]'));
return PasswordValidator(
hasAtLeastEightChars: hasAtLeastEightChars,
hasUpperAndLowerCaseChars: hasUpperAndLowerCaseChars,
hasNumber: hasNumber,
hasSpecialChar: hasSpecialChar,
);
}
),
],
),
),
);
}
}
class PasswordValidator extends StatelessWidget{
final bool hasAtLeastEightChars;
final bool hasUpperAndLowerCaseChars;
final bool hasNumber;
final bool hasSpecialChar;
const PasswordValidator({
super.key,
required this.hasAtLeastEightChars,
required this.hasUpperAndLowerCaseChars,
required this.hasNumber,
required this.hasSpecialChar
});
@override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
PasswordConditionIndicator(
isValid: hasAtLeastEightChars,
title: 'At least 8 characters',
),
PasswordConditionIndicator(
isValid: hasUpperAndLowerCaseChars,
title: 'Upper and lower case characters',
),
PasswordConditionIndicator(
isValid: hasNumber,
title: '1 or more numbers',
),
PasswordConditionIndicator(
isValid: hasSpecialChar,
title: '1 or more special characters',
),
],
);
}
}
class PasswordConditionIndicator extends StatelessWidget{
final bool isValid;
final String title;
const PasswordConditionIndicator({
super.key,
required this.isValid,
required this.title,
});
@override
Widget build(BuildContext context) {
return Row(
children: [
if(isValid) const Icon(Icons.check),
Text(title),
]
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment