How to pass parameters through Java Validator messages?

最后都变了- 提交于 2020-01-14 14:37:11

问题


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:


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.


来源:https://stackoverflow.com/questions/31020035/how-to-pass-parameters-through-java-validator-messages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!