Domanda

I am developing an application where the use of constraint composition would be of great value.

For example, instead of:

@Size(min=1, max=60)
@Pattern(regexp = "[a-zA-Z0-9]*")
protected String invoiceNumber;

I would be able to just write:

@ValidInvoiceNumber
protected String invoiceNumber;

With the following annotation:

@Size(min=1, max=60)
@Pattern(regexp = "[a-zA-Z0-9]*")
@ReportAsSingleViolation
@Target({ METHOD, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = {})
@Documented
public @interface ValidInvoiceNumber {
    String message() default "{someMessageCode}";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

The problem I am facing is that I would like the constraint violation message that is being returned from the validation to not be some generic @ValidInvoiceNumber message (like someMessageCode above), but instead to be the message of the actual annotation that failed. So for example, if the size check failed, I'll get back a Size error default message. If the Pattern message failed, I'll get the Pattern error default message.

Currently I am just getting the general @ValidInvoiceNumber message which isn't providing enough information to the user.

Thanks for your help.

È stato utile?

Soluzione

Just remove @ReportAsSingleViolation. This will give you an ConstraintViolation for each failing constraint. In fact this also ensures that all constraints are validated. With @ReportAsSingleViolation validation stops on the first validation error, returning the message from your main annotation (ValidInvoiceNumber) in your case. See also the relevant Bean Validation specification section - http://beanvalidation.org/1.1/spec/#constraintsdefinitionimplementation-constraintcomposition

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top