How to handle TextField validation in password in Flutter

前端 未结 5 1007
悲哀的现实
悲哀的现实 2020-12-29 08:34

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
相关标签:
5条回答
  • 2020-12-29 09:01

    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

    0 讨论(0)
  • 2020-12-29 09:08

    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");
    
       }
    
    0 讨论(0)
  • 2020-12-29 09:14

    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
     (?=.*?[!@#\$&*~]).{8,}  // should contain at least one Special character
    $
    

    Match above expression with your password string.Using this method-

    String validatePassword(String value) {
        Pattern pattern =
            r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!@#\$&*~]).{8,}$';
        RegExp regex = new RegExp(pattern);
        print(value);
        if (value.isEmpty) {
          return 'Please enter password';
        } else {
          if (!regex.hasMatch(value))
            return 'Enter valid password';
          else
            return null;
        }
      }
    
    0 讨论(0)
  • 2020-12-29 09:17

    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 
        }
    
    0 讨论(0)
  • 2020-12-29 09:17

    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.

    0 讨论(0)
提交回复
热议问题