44

I created a login page and I need to add these things to my password. How do I do it with validation alert message?

  • Minimum 1 Upper case
  • Minimum 1 lowercase
  • Minimum 1 Numeric Number
  • Minimum 1 Special Character
  • Common Allow Character ( ! @ # $ & * ~ )

10 Answers 10

95

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; } } } 
Sign up to request clarification or add additional context in comments.

5 Comments

how to validate this one? •Common Allow Character ( ! @ # $ & * ~ )
"(?=.*?[!@#\$&*~])" part of regex will compare common characters of your password string.
Beware the aliens! The explanation is not describing the same regex. The explanation misses some ? chars.
More special characters validation: (?=.*?[!@#\$&*~`)\%\-(_+=;:,.<>/?"'[{\]}\|^])
How if my password is Temp'12, Temp"12 ???
50

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 } 

1 Comment

is it only way to true, Vignesh123! : true.. is this also wokring? !123viGnesh
4

You can achieve this using below flutter plugin.

wc_form_validators

You can use it something like this:

 TextFormField( decoration: InputDecoration( labelText: 'Password', ), validator: Validators.compose([ Validators.required('Password is required'), Validators.patternString(r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!@#\$&*~]).{8,}$', 'Invalid Password') ]), ), 

Its documentation is really good. You can read it for more util functions like this.

Comments

3

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

2 Comments

How to check upper and lower and special character as I mention in my question?
you can use a RegExp rom dart:core package: api.dartlang.org/stable/2.3.1/dart-core/RegExp-class.html
3

By using extension in dart

extension PasswordValidator on String { bool isValidPassword() { return RegExp( r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!@#\$&*~]).{8,}$') .hasMatch(this); } } 

You can apply this in your textfield like

TextFormField( autovalidate: true, validator: (input) => input. isValidPassword() ? null : "Check your password...", ) 

Comments

3

Flutter Login Validation

 ///creating Username and Password Controller. TextEditingController username=TextEditingController(); TextEditingController password=TextEditingController(); Form( child: Builder( builder: (context) { return Column( children: [ TextFormField( controller: username, validator: (CurrentValue){ var nonNullValue=CurrentValue??''; if(nonNullValue.isEmpty){ return ("username is required"); } if(!nonNullValue.contains("@")){ return ("username should contains @"); } return null; }, ), TextFormField( controller: password, validator: (PassCurrentValue){ RegExp regex=RegExp(r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!@#\$&*~]).{8,}$'); var passNonNullValue=PassCurrentValue??""; if(passNonNullValue.isEmpty){ return ("Password is required"); } else if(passNonNullValue.length<6){ return ("Password Must be more than 5 characters"); } else if(!regex.hasMatch(passNonNullValue)){ return ("Password should contain upper,lower,digit and Special character "); } return null; }, ), ElevatedButton(onPressed: (){ if(Form.of(context)?.validate()?? false){ Navigator.of(context).push(MaterialPageRoute(builder: (_)=>loginpage())); } }, child: Text("Login")) ], ); } ), ) 

in this picture you can see when you Enter inValid username and password it will not Navigate to another page.

when you Enter Valid Username and Password it will Navigate to another Page.

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
3
 import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:flutter_pw_validator/flutter_pw_validator.dart'; import 'Card_Creation.dart'; class SignUp extends StatefulWidget { const SignUp({Key? key}) : super(key: key); @override State<SignUp> createState() => _SignUpState(); } class _SignUpState extends State<SignUp> { TextEditingController _useremail = TextEditingController(); TextEditingController _userpass = TextEditingController(); final _formKey = GlobalKey<FormState>(); @override void dispose() { _useremail.dispose(); _userpass.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( body: Padding( padding: const EdgeInsets.all(20.0), child: SizedBox( width: MediaQuery.of(context).size.width, height: MediaQuery.of(context).size.height, child: Center( child: Form( key: _formKey, child: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: [ const Text( 'Sign Up here....!', style: TextStyle( color: Colors.black, fontWeight: FontWeight.bold, fontSize: 25), ), const SizedBox( height: 10, ), TextFormField( validator: (value) { var availableValue = value ?? ''; if (availableValue.isEmpty) { return ("Username is required"); } if (!availableValue.contains("@") || !availableValue.endsWith("gmail.com")) { return ("Username should be a valid Gmail address"); } return null; }, controller: _useremail, keyboardType: TextInputType.emailAddress, obscureText: false, decoration: InputDecoration( hintText: 'Your email address', enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(20), borderSide: const BorderSide(color: Colors.blueGrey)), focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(20), borderSide: const BorderSide(color: Colors.greenAccent), ), ), ), const SizedBox( height: 10, ), TextFormField( validator: (value) { if (value == null || value.isEmpty) { return "Password is required"; } // Perform custom password validation here if (value.length < 8) { return "Password must be at least 8 characters long"; } if (!value.contains(RegExp(r'[A-Z]'))) { return "Password must contain at least one uppercase letter"; } if (!value.contains(RegExp(r'[a-z]'))) { return "Password must contain at least one lowercase letter"; } if (!value.contains(RegExp(r'[0-9]'))) { return "Password must contain at least one numeric character"; } if (!value.contains(RegExp(r'[!@#\$%^&*()<>?/|}{~:]'))) { return "Password must contain at least one special character"; } return null; // Password is valid. }, controller: _userpass, keyboardType: TextInputType.visiblePassword, obscureText: true, decoration: InputDecoration( hintText: 'Enter Your password', enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(20), borderSide: const BorderSide(color: Colors.blueGrey)), focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(20), borderSide: const BorderSide(color: Colors.greenAccent), ), ), ), const SizedBox( height: 10, ), FlutterPwValidator( controller: _userpass, minLength: 8, uppercaseCharCount: 1, lowercaseCharCount: 1, numericCharCount: 1, specialCharCount: 1, width: 200, height: 150, onSuccess: () { return null; // Password is valid. }, ), const SizedBox( height: 10, ), Align( alignment: Alignment.center, child: ElevatedButton( onPressed: () { if (_formKey.currentState!.validate()) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('Processing Data')), ); _signup(); } }, child: const Text('Register'), ), ), const SizedBox( height: 10, ), ], ), ), ), ), ), ), ); } void _routing_with_clearfields() { _useremail.clear(); _userpass.clear(); _snackonsignup(); // Navigate to the next screen using Navigator. Navigator.of(context).pushReplacement( MaterialPageRoute(builder: (context) => MyCard()), ); } void _signup() async { try { await FirebaseAuth.instance.createUserWithEmailAndPassword( email: _useremail.text.trim(), password: _userpass.text); _routing_with_clearfields(); } on FirebaseAuthException catch (e) { if (e.code == 'weak-password') { print('The password provided is too weak.'); } else if (e.code == 'email-already-in-use') { print('The account already exists for that email.'); } } catch (e) { print(e); } } void _snackonsignup() { final snack = SnackBar( content: const Text( 'SignUp successfully', style: TextStyle(color: Colors.black, fontSize: 15), ), backgroundColor: Colors.lightGreen.shade300, ); ScaffoldMessenger.of(context).showSnackBar(snack); } } Use this code it validates with using flutter package: flutter_pw_validator: ^1.6.0 

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
1

here is the complete answer

Write a Dart program to check whether a string is a valid password. a. A password must have at least ten characters. b. A password consists of only letters and digits. c. A password must contain at least two digits.

import 'dart:io'; main() { var password; stdout.write("Enter You'r Password: "); password=stdin.readLineSync(); if(password.length>=10 && !password.contains(RegExp(r'\W')) && RegExp(r'\d+\w*\d+').hasMatch(password)) { print(" \n\t$password is Valid Password"); } else { print("\n\t$password is Invalid Password"); } 

Comments

0
validator: (value) { password = value; var passwordvalid = RegExp( r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!@#\$&*~]).{8,}$').hasMatch(value!); if (value.isEmpty) { return "Enter Password"; } if (!passwordvalid) { return "Your Password is In-Valid"; } }, 

2 Comments

Check this one Password with UpperCase letters, lowercase letters, numbers, and special character
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
-1
this is the best regx bool passValid = RegExp("^(?=.{8,32}\$)(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[!@#\$%^&*(),.?:{}|<>]).*").hasMatch(value); if (value.isEmpty ||!passValid) { return 'error'; } 

1 Comment

regexp is wrong

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.