BIS Tech
BIS Tech

Reputation: 19444

How to handle TextField validation in password in Flutter

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

Upvotes: 44

Views: 100748

Answers (10)

Ahmad Raza
Ahmad Raza

Reputation: 1

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";
                  }
                },

Upvotes: 0

DevMukh
DevMukh

Reputation: 29

    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

Upvotes: 3

Fayaz Ashraf
Fayaz Ashraf

Reputation: 71

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.

Upvotes: 3

Aditya Patil
Aditya Patil

Reputation: 1486

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...",
)

Upvotes: 3

Nikhat Shaikh
Nikhat Shaikh

Reputation: 3695

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;
      }
    }
  }

Upvotes: 94

mohamed elyamani
mohamed elyamani

Reputation: 57

this is the best regx

bool passValid = RegExp("^(?=.{8,32}\$)(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[!@#\$%^&*(),.?:{}|<>]).*").hasMatch(value);
 
if (value.isEmpty ||!passValid) 
 {
 return 'error';
 }

Upvotes: -1

Tushar Nikam
Tushar Nikam

Reputation: 1593

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");

   }

Upvotes: 1

Ali Abbas
Ali Abbas

Reputation: 171

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.

Upvotes: 4

Vignesh KM
Vignesh KM

Reputation: 2076

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 
    }

Upvotes: 50

Rubens Melo
Rubens Melo

Reputation: 3305

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

Upvotes: 3

Related Questions