From a50f80cea53ce9c070d520f1591eef3a90d13ea6 Mon Sep 17 00:00:00 2001 From: FroGitHub Date: Sat, 28 Dec 2024 19:36:42 +0200 Subject: [PATCH] add checked exception for validation passwords --- .../basesyntax/PasswordValidationException.java | 5 +++++ .../java/core/basesyntax/PasswordValidator.java | 13 ++++++++++++- src/main/java/core/basesyntax/UserService.java | 9 +++++++++ 3 files changed, 26 insertions(+), 1 deletion(-) diff --git a/src/main/java/core/basesyntax/PasswordValidationException.java b/src/main/java/core/basesyntax/PasswordValidationException.java index c9e7ed3e7..1a7aeebd0 100644 --- a/src/main/java/core/basesyntax/PasswordValidationException.java +++ b/src/main/java/core/basesyntax/PasswordValidationException.java @@ -1,3 +1,8 @@ package core.basesyntax; //write your code here +class PasswordValidationException extends Exception { + public PasswordValidationException(String message) { + super(message); + } +} diff --git a/src/main/java/core/basesyntax/PasswordValidator.java b/src/main/java/core/basesyntax/PasswordValidator.java index d4655c9f5..ac418fa9d 100644 --- a/src/main/java/core/basesyntax/PasswordValidator.java +++ b/src/main/java/core/basesyntax/PasswordValidator.java @@ -1,7 +1,18 @@ package core.basesyntax; public class PasswordValidator { - public void validate(String password, String repeatPassword) { + public void validate(String password, String repeatPassword) + throws PasswordValidationException { + PasswordValidationException exception = new PasswordValidationException("Wrong passwords"); //write your code here + if (password == null || repeatPassword == null) { + throw exception; + } + if (password.length() < 10 && repeatPassword.length() < 10) { + throw exception; + } + if (!password.equals(repeatPassword)) { + throw exception; + } } } diff --git a/src/main/java/core/basesyntax/UserService.java b/src/main/java/core/basesyntax/UserService.java index 52f08d130..844d6031a 100644 --- a/src/main/java/core/basesyntax/UserService.java +++ b/src/main/java/core/basesyntax/UserService.java @@ -1,8 +1,17 @@ package core.basesyntax; public class UserService { + private PasswordValidator passwordValidator = new PasswordValidator(); + public void registerUser(User user) { //write your code here + try { + passwordValidator.validate(user.getPassword(), user.getRepeatPassword()); + } catch (PasswordValidationException e) { + System.out.println("Your passwords are incorrect. Try again."); + return; + } + saveUser(user); } public void saveUser(User user) {