How to handle TextField validation in password in Flutter
You have to use TextFormField widget with validator property.
TextFormField(
validator: (value) {
// add your custom validation here.
if (value.isEmpty) {
return 'Please enter some text';
}
if (value.length < 3) {
return 'Must be more than 2 charater';
}
},
),
Take a look on official docs: https://flutter.dev/docs/cookbook/forms/validation
Your regular expression should look like:
r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!@#\$&*~]).{8,}$
Here is an explanation:
r'^
(?=.*[A-Z]) // should contain at least one upper case
(?=.*[a-z]) // should contain at least one lower case
(?=.*?[0-9]) // should contain at least one digit
(?=.*?[!@#\$&*~]) // should contain at least one Special character
.{8,} // Must be at least 8 characters in length
$
Match above expression with your password string. Using this method-
String? validatePassword(String value) {
RegExp regex =
RegExp(r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!@#\$&*~]).{8,}$');
if (value.isEmpty) {
return 'Please enter password';
} else {
if (!regex.hasMatch(value)) {
return 'Enter valid password';
} else {
return null;
}
}
}
You need to use Regular Expression to validate the structure.
bool validateStructure(String value){
String pattern = r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!@#\$&*~]).{8,}$';
RegExp regExp = new RegExp(pattern);
return regExp.hasMatch(value);
}
output:
Vignesh123! : true
vignesh123 : false
VIGNESH123! : false
vignesh@ : false
12345678? : false
This function will validate the passed value is having the structure or not.
var _usernameController = TextEditingController();
String _usernameError;
...
@override
Widget build(BuildContext context) {
return
...
TextFormField(
controller: _usernameController,
decoration: InputDecoration(
hintText: "Username", errorText: _usernameError),
style: TextStyle(fontSize: 18.0),
),
Container(
width: double.infinity,
height: 50.0,
child: RaisedButton(
onPressed: validate,
child: Text(
"Login",
style: TextStyle(color: Colors.white),
),
color: Theme.of(context).primaryColor,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50.0),
),
),
),
...
}
...
validate(){
if(!validateStructure(_usernameController.text)){
setState(() {
_usernameError = emailError;
_passwordError = passwordError;
});
// show dialog/snackbar to get user attention.
return;
}
// Continue
}