简体   繁体   中英

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
}

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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