ramb0
ramb0

Reputation: 127

Some thing is wrong in this regular expression and i cant figure it out

public void actionPerformed(ActionEvent e) {

    String usernamePat = " ^[a-z0-9]{3,15}&";
    String passwordPat = "((?=.*\\d)(?=.*[A-Za-z]).{6,20})";

    String strName = regname.getText();

    char[] mypass1 = pass1.getPassword();
    String strPass1 = new String(mypass1);

    char[] mypass2 = pass2.getPassword();
    String strPass2 = new String(mypass2);

    if (strName.isEmpty()) {
        obj.info("Please enter your username!", "Error");
        return;
    }

    if (strPass1.isEmpty()) {
        obj.info("Please enter your password!", "Error");
        return;
    }

    if (strPass2.isEmpty()) {
        obj.info("Please enter your password again!", "Error");
        return;
    }

    Pattern patU = Pattern.compile(usernamePat);
    Pattern patP = Pattern.compile(passwordPat);

    Matcher matU = patU.matcher(strName);
    Matcher matP = patP.matcher(strPass1);

    if (matU.matches()) {

        if (matP.matches()) {

            if (strPass1.equals(strPass2)) {

            } else {
                obj.info("Passwords dont match, please confirm it again", "Error");
            }

        } else {
            obj.info("You can only use alphabets/numbers in Password", "Error");
        }

    } else {
        obj.info("Please use only alphabets & numbers in Username", "Error");
    }

}

I got everything write on the place, I'm converting the inputs in strings, then the 3 else conditions are checking for empty fields and it is working fine. After those checks, I added regular expressions and to validate the input, and in that last nested if, I will put JDBC code to insert data into my table, but it's not getting pass the first username validation.

I don't get why, given the following input:

username : maisam123
password : abc123
confirm password: abc123

enter image description here

Upvotes: 2

Views: 66

Answers (2)

AMDcze
AMDcze

Reputation: 526

The end sign is $ and not &. You also have an extra space in the beginning.

^[a-z0-9]{3,15}$

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201447

There is a space at the start of your pattern (" ^[a-z0-9]{3,15}&") and a trailing ampersand (so only String(s) starting with a space and ending in an ampersand would pass). Also, you didn't include capital letters.

String usernamePat = "^[a-z0-9]{3,15}";

but, to allow upper-case letters it should be something like

String usernamePat = "^[A-Za-z0-9]{3,15}";

Upvotes: 2

Related Questions