How to pass parameters through Java Validator messages?

10.2k views Asked by At

Currently, I have something like

@NotNull(message="{err.required}")
@Size(min=1, message="{err.required}")
private String firstName;

In my messages.properties, I have

err.required={0} is required.

It works but it prints out firstName is required. which is ugly. It passed the variable name firstName as parameter in {0}.

How do I pass in something like "First name" instead? So it will become First name is required.

1

There are 1 answers

6
Random42 On BEST ANSWER

You could do something like this:

@NotNull(message="First name {err.required}")
@Size(min=1, message="First name {err.required}")
private String firstName;

@NotNull(message="Last name {err.required}")
@Size(min=1, message="Last name {err.required}")
private String lastName;

and in properties file

err.required= is required. 

or if you want to be more clear, you could add your own annotation and validator:

@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = { NotEmptyValidator.class })
public @interface NotEmpty {

    String message() default "{customMessage} is required.";

    Class<?>[] groups() default { };

    Class<? extends Payload>[] payload() default { };

    String customMessage() default "";
}

public class NotEmptyValidator implements ConstraintValidator<NotEmpty, String>
{
    @Override
    public void initialize(NotEmpty notEmpty)
    {        
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context)
    {
        return value != null && !value.isEmpty();
    }
}

Then your field

@NotEmpty(message="{err.required}"
          customMessage="First name")
private String firstName;

And in properties (although it's not mandatory since you can default the value to this):

err.required={customMessage} is required.