Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass parameters through Java Validator messages?

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.

like image 279
Rey Libutan Avatar asked Jun 24 '15 07:06

Rey Libutan


People also ask

How do I customize default error message from Spring @valid validation?

You can perform validation with Errors/BindingResult object. Add Errors argument to your controller method and customize the error message when errors found. Below is the sample example, errors. hasErrors() returns true when validation is failed.

What is @valid Annotation in Java?

The @Valid annotation ensures the validation of the whole object. Importantly, it performs the validation of the whole object graph. However, this creates issues for scenarios needing only partial validation. On the other hand, we can use @Validated for group validation, including the above partial validation.

What does @validated do?

The @Validated annotation is a class-level annotation that we can use to tell Spring to validate parameters that are passed into a method of the annotated class.


1 Answers

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.
like image 95
Random42 Avatar answered Sep 22 '22 10:09

Random42