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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With