📜  如何在Android中使用正则表达式验证密码?

📅  最后修改于: 2021-05-08 20:22:53             🧑  作者: Mango

正则表达式基本上定义了搜索模式,模式匹配或字符串匹配。它存在于Java.util.regex软件包中。 Java Regex API提供1个接口和3个类。它们是:

  1. MatchResult介面
  2. 配对班
  3. 模式类
  4. PatternSyntaxException类

在Android中使用正则表达式验证密码

例子

在此示例中,我们将在客户端验证电子邮件和密码,这意味着我们不检查电子邮件密码是否存储在某个服务器上并与之匹配,而是将电子邮件密码与预定义的模式进行比较。注意,我们将用Java语言实现该项目。

分步实施

步骤1:创建一个新项目

要在Android Studio中创建新项目,请参阅如何在Android Studio中创建/启动新项目。请注意,选择Java作为编程语言。

步骤2:添加依赖项

为了使用设计支持库,我们需要添加其依赖项。转到Gradle脚本> build.gradle(Module:app)并添加以下依赖项。添加依赖项后,单击立即同步

在继续之前,让我们添加一些颜色属性以增强应用程序栏。转到应用程序> res>值> colors.xml并添加以下颜色属性。

XML
 
    #0F9D58 
    #16E37F 
    #03DAC5 


XML


  
    
  
        
  
    
  
    
  
        
  
    
  
    


Java
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.material.textfield.TextInputLayout;
import java.util.regex.Pattern;
  
public class MainActivity extends AppCompatActivity {
  
    // defining our own password pattern
    private static final Pattern PASSWORD_PATTERN =
            Pattern.compile("^" +
                    "(?=.*[@#$%^&+=])" +     // at least 1 special character
                    "(?=\\S+$)" +            // no white spaces
                    ".{4,}" +                // at least 4 characters
                    "$");
    private TextInputLayout email;
    private TextInputLayout password;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          
        // Referencing email and password
        email = findViewById(R.id.email);
        password = findViewById(R.id.password);
    }
  
    private boolean validateEmail() {
          
        // Extract input from EditText
        String emailInput = email.getEditText().getText().toString().trim();
          
        // if the email input field is empty
        if (emailInput.isEmpty()) {
            email.setError("Field can not be empty");
            return false;
        }
          
        // Matching the input email to a predefined email pattern
        else if (!Patterns.EMAIL_ADDRESS.matcher(emailInput).matches()) {
            email.setError("Please enter a valid email address");
            return false;
        } else {
            email.setError(null);
            return true;
        }
    }
  
    private boolean validatePassword() {
        String passwordInput = password.getEditText().getText().toString().trim();
        // if password field is empty
        // it will display error message "Field can not be empty"
        if (passwordInput.isEmpty()) {
            password.setError("Field can not be empty");
            return false;
        }
          
        // if password does not matches to the pattern
        // it will display an error message "Password is too weak"
        else if (!PASSWORD_PATTERN.matcher(passwordInput).matches()) {
            password.setError("Password is too weak");
            return false;
        } else {
            password.setError(null);
            return true;
        }
    }
  
    public void confirmInput(View v) {
        if (!validateEmail() | !validatePassword()) {
            return;
        }
          
        // if the email and password matches, a toast message 
        // with email and password is displayed
        String input = "Email: " + email.getEditText().getText().toString();
        input += "\n";
        input += "Password: " + password.getEditText().getText().toString();
        Toast.makeText(this, input, Toast.LENGTH_SHORT).show();
    }
}


步骤3:设计布局文件

在这一步中,我们将为我们的应用程序设计布局。转到应用程序> res>布局> activity_main.xml 。在此布局中,我们使用了TextInputLayout来向EditText添加额外的功能,例如,视图下方错误消息的间距。下面是为activity_main.xml文件提供的代码段。

XML格式



  
    
  
        
  
    
  
    
  
        
  
    
  
    

步骤4:使用MainActivity。 Java文件

MainActivity中。 Java文件,我们使用预定义的模式进行电子邮件验证,并定义我们自己的模式进行密码验证。为此,我们定义了两个方法ValidateEmail()ValidatePassword()ValidateEmail()方法使用预定义的电子邮件模式。即,它在输入电子邮件中必须具有“ @”和“。”(点)。如果电子邮件不满足条件,它将显示错误消息“请输入有效的电子邮件地址”。在ValidatePassword()中,我们将自己的模式定义为:

如果密码不满足这些条件中的任何一个,则错误消息将显示为“密码太弱”。如果字段电子邮件或密码中的任何一个为空,则会显示“字段不能为空”。如果电子邮件和密码都符合条件,则将显示一条敬酒消息,其中显示了输入的电子邮件和密码。以下是MainActivity的代码段。 Java文件。

Java

import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.material.textfield.TextInputLayout;
import java.util.regex.Pattern;
  
public class MainActivity extends AppCompatActivity {
  
    // defining our own password pattern
    private static final Pattern PASSWORD_PATTERN =
            Pattern.compile("^" +
                    "(?=.*[@#$%^&+=])" +     // at least 1 special character
                    "(?=\\S+$)" +            // no white spaces
                    ".{4,}" +                // at least 4 characters
                    "$");
    private TextInputLayout email;
    private TextInputLayout password;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          
        // Referencing email and password
        email = findViewById(R.id.email);
        password = findViewById(R.id.password);
    }
  
    private boolean validateEmail() {
          
        // Extract input from EditText
        String emailInput = email.getEditText().getText().toString().trim();
          
        // if the email input field is empty
        if (emailInput.isEmpty()) {
            email.setError("Field can not be empty");
            return false;
        }
          
        // Matching the input email to a predefined email pattern
        else if (!Patterns.EMAIL_ADDRESS.matcher(emailInput).matches()) {
            email.setError("Please enter a valid email address");
            return false;
        } else {
            email.setError(null);
            return true;
        }
    }
  
    private boolean validatePassword() {
        String passwordInput = password.getEditText().getText().toString().trim();
        // if password field is empty
        // it will display error message "Field can not be empty"
        if (passwordInput.isEmpty()) {
            password.setError("Field can not be empty");
            return false;
        }
          
        // if password does not matches to the pattern
        // it will display an error message "Password is too weak"
        else if (!PASSWORD_PATTERN.matcher(passwordInput).matches()) {
            password.setError("Password is too weak");
            return false;
        } else {
            password.setError(null);
            return true;
        }
    }
  
    public void confirmInput(View v) {
        if (!validateEmail() | !validatePassword()) {
            return;
        }
          
        // if the email and password matches, a toast message 
        // with email and password is displayed
        String input = "Email: " + email.getEditText().getText().toString();
        input += "\n";
        input += "Password: " + password.getEditText().getText().toString();
        Toast.makeText(this, input, Toast.LENGTH_SHORT).show();
    }
}

输出:在模拟器上运行

想要一个节奏更快,更具竞争性的环境来学习Android的基础知识吗?
单击此处,前往由我们的专家精心策划的指南,以使您立即做好行业准备!