有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

简化java正则表达式代码以验证密码

我想告诉用户他需要什么,以便他的密码是有效的,当它不符合要求时jlabels会变为红色,当它符合要求时会变为黑色。这是我能做我想做的事的最短途径,但它会存在吗?我附上代码和照片

    private void JB_MostrarActionPerformed(java.awt.event.ActionEvent evt) {                                           

    String password = "";

    password = jPasswordField_pass.getText().trim();

    final String regex = "^(?:(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=.,]).*)[^\\s]{8,}$";

    if (password.equals("")) {
        jl_Error.setText("Please enter your Password.");
        jl_Error.setForeground(Color.red);

    } else if (password.matches(regex) == false) {

        jLabel_infopass.setText("Your password must be between 8 and 64 characters long. It must contain at least three (3) of the below:");
        jLabel_infopass.setForeground(Color.red);

        if (Pattern.matches("(?=.*\\d).*", password) == false) {
            jLabel_infopass3.setText("numbers (0-9)");
            jLabel_infopass3.setForeground(Color.red);
        } else {
            jLabel_infopass3.setText("numbers (0-9)");
            jLabel_infopass3.setForeground(Color.black);
        }
        if (Pattern.matches("(?=.*[a-z]).*", password) == false) {
            jLabel_infopass2.setText("lowercase (a-z)");
            jLabel_infopass2.setForeground(Color.red);
        } else {
            jLabel_infopass2.setText("lowercase (a-z)");
            jLabel_infopass2.setForeground(Color.black);
        }
        if (Pattern.matches("(?=.*[A-Z]).*", password) == false) {
            jLabel_infopass1.setText("uppercase (A-Z)");
            jLabel_infopass1.setForeground(Color.red);
        } else {
            jLabel_infopass1.setText("uppercase (A-Z)");
            jLabel_infopass1.setForeground(Color.black);
        }
        if (Pattern.matches("(?=.*[@#$%^&+!.,]).*", password) == false) {
            jLabel_infopass4.setText("symbols (e.g. #, $, !, @, ^, &, *, etc)");
            jLabel_infopass4.setForeground(Color.red);
        } else {
            jLabel_infopass4.setText("symbols (e.g. #, $, !, @, ^, &, *, etc)");
            jLabel_infopass4.setForeground(Color.black);
        }

    } else {
        jLabel_infopass.setText("Your password must be between 8 and 64 characters long. It must contain at least three (3) of the below:");
        jLabel_infopass.setForeground(Color.black);
        JOptionPane.showMessageDialog(null, password);
    }
} 

capture run box


共 (0) 个答案