Input validation is a critical process of ensuring that user-provided data meets specific criteria before processing. It serves as the first line of defense against potential security vulnerabilities and data integrity issues.
Validation Approaches
1. Regular Expression Validation
Regular expressions provide powerful pattern matching for input validation:
public class RegexValidation {
// Email validation
public static boolean isValidEmail(String email) {
String emailRegex = "^[A-Za-z0-9+_.-]+@(.+)$";
return email.matches(emailRegex);
}
// Phone number validation
public static boolean isValidPhoneNumber(String phone) {
String phoneRegex = "^\\+?\\d{10,14}$";
return phone.matches(phoneRegex);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter email: ");
String email = scanner.nextLine();
System.out.println("Valid email: " + isValidEmail(email));
System.out.print("Enter phone number: ");
String phone = scanner.nextLine();
System.out.println("Valid phone: " + isValidPhoneNumber(phone));
}
}
Validation Flow
flowchart TD
A[User Input] --> B{Validation Check}
B --> |Pass| C[Process Input]
B --> |Fail| D[Reject Input]
D --> E[Provide Error Feedback]
2. Comprehensive Validation Framework
A more robust validation approach:
public class ComprehensiveValidator {
public static class ValidationResult {
private boolean valid;
private List<String> errors;
public ValidationResult() {
this.valid = true;
this.errors = new ArrayList<>();
}
public void addError(String error) {
valid = false;
errors.add(error);
}
public boolean isValid() {
return valid;
}
public List<String> getErrors() {
return errors;
}
}
public static ValidationResult validateUserInput(String username, int age, String email) {
ValidationResult result = new ValidationResult();
// Username validation
if (username == null || username.length() < 3 || username.length() > 20) {
result.addError("Username must be between 3 and 20 characters");
}
// Age validation
if (age < 18 || age > 120) {
result.addError("Age must be between 18 and 120");
}
// Email validation
if (!email.matches("^[A-Za-z0-9+_.-]+@(.+)$")) {
result.addError("Invalid email format");
}
return result;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter username: ");
String username = scanner.nextLine();
System.out.print("Enter age: ");
int age = scanner.nextInt();
scanner.nextLine(); // Consume newline
System.out.print("Enter email: ");
String email = scanner.nextLine();
ValidationResult validationResult = validateUserInput(username, age, email);
if (validationResult.isValid()) {
System.out.println("Input is valid");
} else {
System.out.println("Validation Errors:");
validationResult.getErrors().forEach(System.out::println);
}
}
}
Validation Strategy Comparison
Validation Type |
Approach |
Complexity |
Use Case |
Simple Regex |
Pattern matching |
Low |
Basic format checks |
Comprehensive |
Multiple criteria |
High |
Complex input validation |
Custom Validation |
Specific business rules |
Medium |
Domain-specific checks |
Advanced Validation Techniques
3. Custom Validation Annotations
Implement custom validation using annotations for more flexible validation:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ValidAge {
int min() default 18;
int max() default 120;
String message() default "Invalid age range";
}
Best Practices
- Validate input as early as possible
- Use multiple validation layers
- Provide clear error messages
- Never trust user input
- Implement server-side validation
LabEx recommends developing a comprehensive validation strategy that combines multiple techniques to ensure robust and secure input handling in Java applications.