Embed strings inside localized validation error messages

23 hours ago 3
ARTICLE AD BOX

I configured localization in my project. I have generic validation error messages with placeholders, and field names, such as these.

src/main/resources/lang/messages.properties:

field.NotBlank=Polje {field} je obavezno. # ... email=imejl adresa

A DTO class whose fields have annotations for validation.

src/main/java/com.example.realestate/dtos/auth/LoginDTO:

@Data @ConfirmPassword public class RegisterDTO { @NotBlank(message = "{email.NotBlank}") @Email(message = "{email.Email}") private String email; @NotBlank(message = "{password.NotBlank}") @Password private String password; @NotBlank(message = "{password2.NotBlank}") private String password2; @NotBlank(message = "{phone.NotBlank}") @Pattern(regexp = "^\\+381 \\d{2} \\d{6,7}$", message = "{phone.Pattern}") private String phone; @NotBlank(message = "{firstName.NotBlank}") @Pattern(regexp = "^\\p{L}*$", message = "{firstName.Alpha}") private String firstName; @NotBlank(message = "{lastName.NotBlank}") @Pattern(regexp = "^\\p{L}*$", message = "{lastName.Alpha}") private String lastName; @NotNull(message = "{birthDate.NotNull}") @Adult @DateTimeFormat(pattern = "yyyy-MM-dd") private LocalDate birthDate; }

Have a badly formatted controller method that uses the DTO object, because I can't re-indent the code with TAB key in this site (it switches to next form field).

@PostMapping("/registracija") public String register(Model model, HttpServletRequest request, RedirectAttributes attributes, @ModelAttribute("dto") @Valid RegisterDTO dto, BindingResult result) { // 2 Input validation & sanitization if (result.hasErrors()) { model.addAttribute("dto", dto); // 5 Security logging logger.error("Registration failed due to validation errors."); return "auth/register"; } if (userServ.existsByEmail(dto.getEmail())) { String fail = "Korisnik sa ovom imejl adresom već postoji."; attributes.addFlashAttribute("fail", fail); // 5 Security logging logger.error("Registration failed because an user with the provided email address already exists."); return "redirect:/registracija"; } if (userServ.existsByPhone(dto.getPhone())) { String fail = "Korisnik sa ovim brojem telefona već postoji."; attributes.addFlashAttribute("fail", fail); // 5 Security logging logger.error("Registration failed because an user with the provided phone number already exists."); return "redirect:/registracija"; } CustomUser user = userServ.create(dto); try { request.login(user.getEmail(), user.getPassword()); // 5 Security logging logger.info("User {} registered successfully.", user); return "redirect:/oglasi"; } catch (ServletException e) { throw new RuntimeException(e); } } // [1]

How do I insert email from messages.properties into field.NotBlank from messages.properties in the DTO class?

I mean directly inserting/embedding "{email}" into "{field.NotBlank}" in @NotBlank attribute.

Read Entire Article