I'm working on a school assignment that validates emails without using Regex. The premise of this exercise is to learn about methods and to practice our critical thinking. I understand that the code can be reduced to fewer lines.
Right now, I need to check all conditions for the prefix of an email (The characters before '@'):
Examples of valid prefixes are: “abc-d”, “abc.def”, “abc”, “abc_def”.
Examples of invalid prefixes are: “abc-”, “abc..d”, “.abc”, “abc#def”.
I'm having a hard time figuring out the third condition. So far, I have these methods that meet the other conditions.
public static boolean isAlphanumeric(char c) {
return Character.isLetterOrDigit(c);
}
public static boolean isValidPrefixChar(char preChar) {
char[] prefixChar = new char[] {'-', '.', '_'};
for (int i = 0; i < prefixChar.length; i++) {
if (prefixChar[i] == preChar) {
return true;
} else if (isAlphanumeric(preChar)) {
return true;
}
}
return false;
}
public static boolean isValidPrefix(String emailPrefix) {
boolean result = false;
// To check if first character is alphanumeric
if (isAlphanumeric(emailPrefix.charAt(0)) && emailPrefix.length() > 1) {
for (int i = 0; i < emailPrefix.length(); i++) {
// If email prefix respects all conditions, change result to true
if (isValidPrefixChar(emailPrefix.charAt(i))) {
result = true;
} else {
result = false;
break;
}
}
}
return result;
}
Let's look at your list:
As you say, 1, 2, and 4 are easy. Here's what I would do. My first line would check length and return false if incorrect. I would then iterate over the characters. Inside the loop;
Should be about 10 lines of easily-readable code.