Question

Is there a way to add variables in Dropwizard's validation error message? Something in the effect of

@ValidationMethod(message=String.format("Url cannot be null, field value = %s", fieldValue))
public boolean isNotValid() {
    String fieldValue = this.getFieldValue();
    return this.url == null;
}

I just want to add variable into the error message.

Was it helpful?

Solution

I found an answer. Hibernate 5.1 has error message interpolation which kinda takes care of this.

@Size(min = 0, max = 0, message="${validatedValue} is present"))
public String getErrorMessage() {
    List<String> illegalValues = ImmutableList.of("illegal value");
    return illegalValues;
}

It's a little hacky, but it solves the problem. Take a look at http://docs.jboss.org/hibernate/validator/5.1/reference/en-US/html/chapter-message-interpolation.html

OTHER TIPS

I found a proper way to validate beans - don't use dropwizard's @ValidationMethod, but instead define your own annotation and validator:

@Target({TYPE, ANNOTATION_TYPE})
@Retention(RUNTIME)
@Constraint(validatedBy = MyValidator.class})
@Documented
public @interface ValidPerson {
    String message() default "Bad person ${validatedValue.name}";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

class MyValidator implements ConstraintValidator<ValidPerson,Person> {
    @Override
    public void initialize(ValidPerson annotaion) {}

    @Override
    public boolean isValid(Person p, ConstraintValidatorContext context) {
        return false; //let's say every person is invalid :-)
     }
}

I'm unfamiliar with Dropwizard, but Java's annotations are simply compile-time metadata. You can't call methods in annotation declarations simply because the Java compiler does not perform the same compile-time code execution as some other compilers, such as C or C++.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top