The following code should test 2 strings (username and password) for length and allowed characters (should be 0-9. a-z, A-Z). the legalCharacters ArrayList is filled with characters a-z and 0-9.
testing for appropriate length works, but not for legal characters this test returns an illegal characters error in the username: user: aba pass: aba
public DataResponseType checkForDataErrors(String username, String password) {
responseType = null;
boolean isIllegalUsername = false;
boolean isIllegalPassword = false;
if (username.length() < 3 || username.length() > 15) {
responseType = DataResponseType.INVALID_USERNAME_LENGTH;
} else if (password.length() < 3 || password.length() > 15) {
responseType = DataResponseType.INVALID_PASSWORD_LENGTH;
} else {
for (int x = 0; x < username.length(); x++) {
for (int z = 0; z < legalCharacters.size(); z++) {
Character test = username.toLowerCase().charAt(x);
if (!test.equals(legalCharacters.get(z))) {
if (z == legalCharacters.size() - 1) {
isIllegalUsername = true;
break;
}
}
}
if (isIllegalUsername) {
break;
}
}
for (int x = 0; x < password.length(); x++) {
for (int z = 0; z < legalCharacters.size(); z++) {
Character test = password.toLowerCase().charAt(x);
if (!test.equals(legalCharacters.get(z))) {
if (z == legalCharacters.size() - 1) {
isIllegalPassword = true;
break;
}
}
}
if (isIllegalPassword) {
break;
}
}
if (isIllegalUsername) {
responseType = DataResponseType.INVALID_USERNAME_CHARACTERS;
} else if (isIllegalPassword) {
responseType = DataResponseType.INVALID_PASSWORD_CHARACTERS;
} else {
responseType = DataResponseType.VALID;
}
}
return responseType;
}
Does anybody know how to fix this? or do it in a easier way (I don't understand how predicates work and haven't been able to find a good explanation)? If other code is needed, please ask.