I created a login page and I need to add these things to my password. How do I do it with validation alert message?
In this example, learn how to add validation to a form that has a single text field using the following steps: Create a Form with a GlobalKey . Add a TextFormField with validation logic. Create a button to validate and submit the form.
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 }
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; } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With