简体   繁体   English

如何在 Flutter 中处理密码中的 TextField 验证

[英]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?如何使用验证警报消息执行此操作?

  • Minimum 1 Upper case最少 1 个大写
  • Minimum 1 lowercase最少 1 个小写字母
  • Minimum 1 Numeric Number最少 1 个数字
  • Minimum 1 Special Character最少 1 个特殊字符
  • Common Allow Character ( ! @ # $ & * ~ )通用允许字符 (!@#$ & *~)

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 
    }

You have to use TextFormField widget with validator property.您必须使用带有验证器属性的 TextFormField 小部件。

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查看官方文档: https ://flutter.dev/docs/cookbook/forms/validation

You can achieve this using below flutter plugin.您可以使用下面的颤振插件来实现这一点。

wc_form_validators 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.您可以阅读它以了解更多类似这样的实用功能。

here is the complete answer这是完整的答案

Write a Dart program to check whether a string is a valid password.编写一个 Dart 程序来检查一个字符串是否是一个有效的密码。 a.一个。 A password must have at least ten characters.密码必须至少有十个字符。 b.湾。 A password consists of only letters and digits.密码仅由字母和数字组成。 c. 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");

   }
this is the best regx

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

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

Flutter Login Validation Flutter 登录验证

  ///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.当您输入有效的用户名和密码时,它将导航到另一个页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM