import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class EntryValidator {
/**
* Validates a single entry based on predefined rules.
* @param entry The entry to validate.
* @param validationRules A map of field names to validation functions.
* @return A map of error messages. Empty if no errors found.
*/
public static Map<String, String> validateEntry(String entry, Map<String, ValidationFunction> validationRules) {
Map<String, String> errors = new HashMap<>();
for (Map.Entry<String, ValidationFunction> entryRule : validationRules.entrySet()) {
String fieldName = entryRule.getKey();
ValidationFunction validationFunction = entryRule.getValue();
String fieldValue = getFieldValue(entry, fieldName); // Extract value for field
if (validationFunction.validate(fieldValue)) {
// Validation successful, no error
} else {
errors.put(fieldName, validationFunction.getErrorMessage());
}
}
return errors;
}
/**
* Extracts the value of a specific field from the entry string.
* @param entry The entry string.
* @param fieldName The name of the field.
* @return The value of the field, or null if not found.
*/
private static String getFieldValue(String entry, String fieldName) {
String regex = "\\b" + fieldName + ":\\s*(.*?)(?:\\n|$)\\b"; //regex to extract field value
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(entry);
if (matcher.find()) {
return matcher.group(1).trim();
}
return null;
}
/**
* Functional interface for validation functions.
*/
@FunctionalInterface
public interface ValidationFunction {
boolean validate(String value);
String getErrorMessage();
}
public static void main(String[] args) {
// Example usage
Map<String, ValidationFunction> rules = new HashMap<>();
// Example rule: Name must be at least 3 characters
rules.put("Name", value -> {
if (value == null) return false;
return value.length() >= 3;
}, "Name must be at least 3 characters.");
// Example rule: Email must be a valid email format
rules.put("Email", value -> {
if (value == null) return false;
String emailRegex = "^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$";
Pattern pattern = Pattern.compile(emailRegex);
return pattern.matcher(value).matches();
}, "Invalid email format.");
// Example rule: Age must be a number between 0 and 150
rules.put("Age", value -> {
if(value == null) return false;
try {
int age = Integer.parseInt(value);
return age >= 0 && age <= 150;
} catch (NumberFormatException e) {
return false;
}
}, "Age must be a number between 0 and 150.");
String entry1 = "Name: John Doe\nEmail: john.doe@example.com\nAge: 30";
String entry2 = "Name: Jo\nEmail: invalid-email\nAge: 200";
String entry3 = "Name: Jane\nEmail: jane@example.com\nAge: abc";
System.out.println("Entry 1 Errors: " + validateEntry(entry1, rules));
System.out.println("Entry 2 Errors: " + validateEntry(entry2, rules));
System.out.println("Entry 3 Errors: " + validateEntry(entry3, rules));
}
}
Add your comment