Dans cette étape finale, nous allons construire un système complet de validation de formulaire qui intègre toutes les techniques que nous avons apprises. Nous allons créer un système de validation plus modulaire et réutilisable qui peut être facilement étendu pour différentes applications.
Création d'une classe utilitaire de validation
Commençons par créer une classe utilitaire qui encapsule nos méthodes de validation :
-
Créez un nouveau fichier nommé InputValidator.java dans le WebIDE.
-
Ajoutez le code suivant au fichier :
import java.util.regex.Pattern;
import java.util.regex.Matcher;
/**
* Utility class for validating user input
*/
public class InputValidator {
// Regular expression patterns
private static final String USERNAME_PATTERN = "^[a-zA-Z0-9_]{3,15}$";
private static final String EMAIL_PATTERN = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
private static final String PHONE_PATTERN = "^\\d{3}-\\d{3}-\\d{4}$";
private static final String PASSWORD_PATTERN = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])(?=\\S+$).{8,}$";
/**
* Validates a username
* @param username The username to validate
* @return true if the username is valid, false otherwise
*/
public static boolean isValidUsername(String username) {
if (username == null) {
return false;
}
Pattern pattern = Pattern.compile(USERNAME_PATTERN);
Matcher matcher = pattern.matcher(username);
return matcher.matches();
}
/**
* Validates an email address
* @param email The email to validate
* @return true if the email is valid, false otherwise
*/
public static boolean isValidEmail(String email) {
if (email == null) {
return false;
}
Pattern pattern = Pattern.compile(EMAIL_PATTERN);
Matcher matcher = pattern.matcher(email);
return matcher.matches();
}
/**
* Validates a phone number
* @param phone The phone number to validate
* @return true if the phone number is valid, false otherwise
*/
public static boolean isValidPhone(String phone) {
if (phone == null) {
return false;
}
Pattern pattern = Pattern.compile(PHONE_PATTERN);
Matcher matcher = pattern.matcher(phone);
return matcher.matches();
}
/**
* Validates an age
* @param age The age to validate
* @return true if the age is valid, false otherwise
*/
public static boolean isValidAge(int age) {
return age >= 0 && age <= 120;
}
/**
* Validates a password
* @param password The password to validate
* @return true if the password is valid, false otherwise
*/
public static boolean isValidPassword(String password) {
if (password == null) {
return false;
}
Pattern pattern = Pattern.compile(PASSWORD_PATTERN);
Matcher matcher = pattern.matcher(password);
return matcher.matches();
}
/**
* Gets the error message for an invalid username
* @return The error message
*/
public static String getUsernameErrorMessage() {
return "Username must be 3-15 characters long and contain only letters, numbers, or underscores.";
}
/**
* Gets the error message for an invalid email
* @return The error message
*/
public static String getEmailErrorMessage() {
return "Please enter a valid email address.";
}
/**
* Gets the error message for an invalid phone number
* @return The error message
*/
public static String getPhoneErrorMessage() {
return "Please enter a valid phone number in the format 123-456-7890.";
}
/**
* Gets the error message for an invalid age
* @return The error message
*/
public static String getAgeErrorMessage() {
return "Age must be between 0 and 120.";
}
/**
* Gets the error message for an invalid password
* @return The error message
*/
public static String getPasswordErrorMessage() {
return "Password must be at least 8 characters long and contain at least one digit, one lowercase letter, one uppercase letter, one special character, and no whitespace.";
}
}
- Enregistrez le fichier en appuyant sur
Ctrl+S.
Maintenant, créons une nouvelle version de notre formulaire d'inscription qui utilise la classe InputValidator :
-
Créez un nouveau fichier nommé CompleteRegistrationForm.java dans le WebIDE.
-
Ajoutez le code suivant au fichier :
import java.util.Scanner;
public class CompleteRegistrationForm {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Collect and validate user information
String username = getValidInput(scanner, "Username", InputValidator::isValidUsername, InputValidator.getUsernameErrorMessage());
int age = getValidAge(scanner);
String email = getValidInput(scanner, "Email", InputValidator::isValidEmail, InputValidator.getEmailErrorMessage());
String phone = getValidInput(scanner, "Phone number (format: 123-456-7890)", InputValidator::isValidPhone, InputValidator.getPhoneErrorMessage());
String password = getValidInput(scanner, "Password", InputValidator::isValidPassword, InputValidator.getPasswordErrorMessage());
// Display the registration information
System.out.println("\nRegistration Successful!");
System.out.println("Username: " + username);
System.out.println("Age: " + age);
System.out.println("Email: " + email);
System.out.println("Phone: " + phone);
System.out.println("Password: " + maskPassword(password));
scanner.close();
}
/**
* Generic method to get valid input from the user
* @param scanner The scanner to read input
* @param fieldName The name of the field being validated
* @param validator The validation function
* @param errorMessage The error message to display
* @return The validated input
*/
private static String getValidInput(Scanner scanner, String fieldName, java.util.function.Predicate<String> validator, String errorMessage) {
String input;
boolean validInput = false;
do {
System.out.print("Enter your " + fieldName + ": ");
input = scanner.nextLine().trim();
if (!validator.test(input)) {
System.out.println("Error: " + errorMessage);
} else {
validInput = true;
}
} while (!validInput);
return input;
}
/**
* Gets a valid age from the user
* @param scanner The scanner to read input
* @return The validated age
*/
private static int getValidAge(Scanner scanner) {
int age = 0;
boolean validAge = false;
while (!validAge) {
try {
System.out.print("Enter your age (0-120): ");
age = Integer.parseInt(scanner.nextLine());
if (!InputValidator.isValidAge(age)) {
System.out.println("Error: " + InputValidator.getAgeErrorMessage());
} else {
validAge = true;
}
} catch (NumberFormatException e) {
System.out.println("Error: Please enter a valid numeric age.");
}
}
return age;
}
/**
* Masks a password for display
* @param password The password to mask
* @return The masked password
*/
private static String maskPassword(String password) {
if (password == null || password.isEmpty()) {
return "";
}
return "*".repeat(password.length());
}
}
-
Enregistrez le fichier en appuyant sur Ctrl+S.
-
Compilez les deux fichiers Java :
javac InputValidator.java
javac CompleteRegistrationForm.java
- Exécutez le programme du formulaire d'inscription :
java CompleteRegistrationForm
- Suivez les invitations pour entrer des informations valides pour chaque champ. Le programme validera chaque entrée selon les règles définies dans la classe
InputValidator.
Exemple d'interaction :
Enter your Username: john_doe
Enter your age (0-120): 35
Enter your Email: john.doe@example.com
Enter your Phone number (format: 123-456-7890): 123-456-7890
Enter your Password: weakpw
Error: Password must be at least 8 characters long and contain at least one digit, one lowercase letter, one uppercase letter, one special character, and no whitespace.
Enter your Password: P@ssw0rd123
Registration Successful!
Username: john_doe
Age: 35
Email: john.doe@example.com
Phone: 123-456-7890
Password: ***********
Avantages de cette approche
L'approche que nous avons adoptée dans cet exemple final offre plusieurs avantages :
- Modularité : La logique de validation est séparée dans une classe utilitaire réutilisable.
- Extensibilité : De nouvelles règles de validation peuvent être facilement ajoutées à la classe
InputValidator.
- Maintenabilité : Les messages d'erreur sont centralisés et peuvent être facilement mis à jour.
- Réutilisation du code : La méthode
getValidInput est générique et peut être utilisée pour différents types d'entrées.
- Sécurité : Le mot de passe est masqué lorsqu'il est affiché à l'utilisateur.
Cette conception suit les bonnes pratiques d'ingénierie logicielle et facilite l'adaptation du système de validation pour différentes applications.