Reputation: 19120
I'm using Spring 5.1. I want to write a validator for a form I'm submitting and I would like to customize one of the error messages that comes back. I have the error message stored in a properties file ...
already.taken.registration.username=There is already an account created with the username {0}. Did you forget your password?
Note the "{0}" for where I would like to insert the invalid username the user has entered. So in my validator I have
import org.springframework.validation.Validator;
...
public class RegistrationFormValidator implements Validator
{
...
@Override
public void validate(final Object target, final Errors errors)
{
final RegistrationForm regForm = (RegistrationForm) target;
if (regForm != null &&
!StringUtils.isEmpty(regForm.getEmail()) &&
userWithEmail(regForm.getEmail()) ) {
errors.rejectValue("email", "already.taken.registration.username", regForm.getEmail());
} // if
However, when the specific branch is run, the {0} isn't getting populated, despite the fact I've verified that "regForm.getEmail()" is non-empty. I see this printed to my JSP page
There is already an account created with the username {0}. Did you forget your password?
What's the correct way to fill in the error message with custom data?
Upvotes: 0
Views: 1390
Reputation: 2109
errors.rejectValue("email", "already.taken.registration.username", regForm.getEmail());
This will actually call the method
void rejectValue(@Nullable
java.lang.String field,
java.lang.String errorCode,
java.lang.String defaultMessage)
What you need is to add an array of objects with the arguments:
void rejectValue(@Nullable
java.lang.String field,
java.lang.String errorCode,
@Nullable
java.lang.Object[] errorArgs,
@Nullable
java.lang.String defaultMessage)
Your call will be something like this :
errors.rejectValue("email", "already.taken.registration.username", new Object[] {regForm.getEmail()}, null);
Upvotes: 2