0

Spring Boot. I have a service where the parameter is validated

@Override
public void registerUser(
        @Valid RegisterDTO registerDTO
) {

The field that is validated is e. g.

@NotEmpty
@Pattern(regexp = "[a-zA-Z0-9_-]{6,36}")
private String username;

Then I set ExceptionHandler to pick up this exception

@ExceptionHandler(ConstraintViolationException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ValidationErrorDTO processValidationError(ConstraintViolationException ex) {
    ValidationErrorDTO validationErrorDTO = new ValidationErrorDTO();

    Set<ConstraintViolation<?>> set =  ex.getConstraintViolations();

    for (Iterator<ConstraintViolation<?>> iterator = set.iterator();iterator.hasNext(); ) {
        ConstraintViolation<?> next =  iterator.next();

        validationErrorDTO.getFieldErrors()
                .add(new ErrorFieldDTO(((PathImpl)next.getPropertyPath()).getLeafNode().getName(),
                        next.getMessage()));
    }

    return validationErrorDTO;
}

I have a validationMessages. properties file where I keep my bug messages

NotEmpty.registerDTO.username=This field is required.
Pattern.registerDTO.username=Please enter at least 6 characters(max. 36 characters). Only letters, numbers and special characters '_' and '-'.

However, the result of this operation appears to be https://zapodaj.net/d1a4f695e6a7d.png.html

Does not retrieve a local message from the. properties file.

How to set up for local messages to be downloaded from the properties file?

sdfsd
  • 1,027
  • 2
  • 10
  • 15

1 Answers1

1

Well, you have to configure the custom validation messages for Hibernate. The first bean configures the location of the validation messages to the custom validationMessages file (use any name). In the WebMvcConfigurerAdapter you can @Override the getValidator() method which returns the custom Validator.

@Bean(name = "messageSource")
public MessageSource messageSource() {
    ReloadableResourceBundleMessageSource rrbms = new ReloadableResourceBundleMessageSource();
    rrbms.setBasename("classpath:validationMessages");
    rrbms.setDefaultEncoding("UTF-8");
    return rrbms;
}

@Bean(name = "validator")
public LocalValidatorFactoryBean validator() {
    LocalValidatorFactoryBean lvfb = new LocalValidatorFactoryBean();
    lvfb.setValidationMessageSource(messageSource());
    return lvfb;
}

@Override
public Validator getValidator() {
    return validator();
}

Since you are okay with the default name validationMessages.properties or in case you use WebConfigurationSupport, the minimal setup is:

@Override
public Validator getValidator() {
    LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
    validator.setValidationMessageSource(messageSource());
    return validator;
}

Anyway, then you have to refer to the right property using the message.

@Pattern(regexp = "[a-zA-Z0-9_-]{6,36}", message="{Pattern.registerDTO.username}")

A good practice is not to name the property according to a field it is validating, but according to the type of the validation.

validation.notEmpty=This field is required.
validation.pattern.username=Please enter at least 6 characters(max. 36 characters). Only letters, numbers and special characters '_' and '-'.
validation.pattern.email=...
validation.pattern.phone=...
validation.size=...
Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
  • Please enter at least 6 characters(max. 36 characters). I want to get 6 or 36 from another property / variable and I don't want to hardcode it like this in the message how would I go about doing that ? – Denson Oct 04 '21 at 12:13
  • @Denson: Take a look at this answer: https://stackoverflow.com/a/36148965/3764965 You can combine properties. – Nikolas Charalambidis Oct 04 '21 at 12:57