Using parameter 1 without using parameter 0 in Spring Boot messages

418 views Asked by At

In messages.properties file:

validation.title=At least {1} characters

Also LocalValidatorFactoryBean is defined:

@Bean
    public LocalValidatorFactoryBean localValidatorFactoryBean(MessageSource messageSource) {
        LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
        bean.setValidationMessageSource(messageSource);
        return bean;
    }

When I run the code I get the result:

At least {1} characters

But if I change in properties:

validation.title=At least {1} characters {0}

I get the result:

At least 20 characters title

But I do not need the 0 parameters.

Is there a way to fix this?

1

There are 1 answers

0
hicnar On

You're trying to access array parameters and with this approach in order to get that done and have your string interpolated you need to use the one at the index 0 and I have no idea why. There's another way though and with common annotations (haven't tried this with custom annotations) for validating forms this can be solved as follows:

// the form

public class SomeForm {

  @Length(min = 4, max = 16, message="{username.length.error}")
  private String username;

// other stuff

}

In the messages.properties

username.length.error = Username cannot be blank and its length must be between {min} and {max} characters.

So in the message.properties (in this case {min} and {max}) the placeholders must match the names of the params you have on the annotation.