// Define a method that takes an email as a parameter and returns a boolean value
public static Boolean validateEmail(String email) {
// Declare a variable to store the regular expression pattern for a valid email
String pattern = '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}$';
// Create a Pattern object using the pattern
Pattern p = Pattern.compile(pattern);
// Create a Matcher object using the email and the pattern
Matcher m = p.matcher(email);
// Return true if the email matches the pattern, false otherwise
return m.matches();
}
// Define a method that takes a list of emails as a parameter and throws an exception if any of them is invalid
public static void checkEmails(List<String> emails) {
// Loop through the emails
for (String email : emails) {
// Call the validateEmail method and store the result
Boolean isValid = validateEmail(email);
// If the result is false, throw an exception with the invalid email
if (!isValid) {
throw new EmailException('Invalid email: ' + email);
}
}
}
// Define a custom exception class for invalid emails
public class EmailException extends Exception {}
This code will create two methods: one to validate a single email using a regular expression, and another to check a list of emails and throw an exception if any of them is invalid.
The regular expression will reject any email that has numbers at the end, contains the '&' character, or includes the '/' character, as per your scenario.