Benjamin Naesen
Benjamin Naesen

Reputation: 172

Regex validation goes wrong - Java

So I have this row of regex to check my input. There is an input because the else is activated but I can't find it.

Username: Donald
Password: 1234
Name: Donald
LastName: Muylle
Phone: 012121212
Address: Zeverstreet 12
City: Gestel
Job: Bar

if(txtUsername.getText().matches("[a-zA-Z0-9]")
&& txtPassword.getText().matches("[a-zA-Z0-9]") &&
txtName.getText().matches("[a-zA-Z]") && 
txtLastName.getText().matches("[a-zA-Z]") && 
txtPhone.getText().matches("[0-9]") &&
txtAddress.getText().matches("[a-zA-Z0-9\\s]") && 
txtCity.getText().matches("[a-zA-Z]") && 
txtJob.getText().contains("[a-zA-Z]")){
    // Code
} else {
    // Shows Alert
}

Upvotes: 0

Views: 51

Answers (3)

Davide Lorenzo MARINO
Davide Lorenzo MARINO

Reputation: 26956

All your regular expressions match only strings of 1 char. Modify all them adding a + symbol at the end.

So [a-zA-Z0-9] becomes [a-zA-Z0-9]+, [a-zA-Z] becomes [a-zA-Z]+ and so on.

The address regular expression [a-zA-Z0-9\\s] should be [a-zA-Z0-9\s]+ with only one slash

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627609

You have contains in the last check. Replace it with matches.

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174874

All you have to do is to add + quantifier next to all the character classes like,

txtUsername.getText().matches("[a-zA-Z0-9]+")
                                          ^

So that, it would match one or more occurrences of the characters given in the list. Without +, it would match a single character only where the matches method must check for a match against the whole string. So this would end up in failure if the input contain more than one character.

Upvotes: 1

Related Questions