Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why must JSR303 custom annotation's constrain group default to empty array?

I'm writing a custom validator for a specific constrain group (not Default), but the runtime gives me the below error.

I'm just curious why they need the default values to be empty. Appreciate if you can share your opinion. Thanks :)

xxx.model.validation.CustomValidation contains Constraint annotation, but the groups parameter default value is not the empty array.

StackTrace: org.hibernate.validator.metadata.ConstraintHelper.assertGroupsParameterExists(ConstraintHelper.java:335) org.hibernate.validator.metadata.ConstraintHelper.isConstraintAnnotation(ConstraintHelper.java:282)

like image 259
The Huy Avatar asked Nov 04 '22 19:11

The Huy


1 Answers

I can't figure out in which scenario it can be useful to bind a constraint to a specific group.

A group is used for partial validation (and sequence validation). If you have 10 fields in a class you can mark 8 of them with A and 2 with B. Then you can decide to validate only the fields in the A group or in the B group. Conversely you want that @MyConstraint belongs to a specific group named C. It makes no sense. A group is more or less a name used to distinguish some fields from others in the same class. It has no absolute meaning. Groups are useful in validation not in constraint definition, they are related to fields not to constraints.

Furthermore if you hide the group name in the constraint definition you may run into errors because you can think that the fields are validated all togheter.

@Email
private String mail;

@Password
private String pass;

@VAT
private String vatCode;

Are you able to see if there is a partial validation?

EDIT

In relation to the second comment: Suppose you have a class with 5 fields with no constraint at all. Three of them are integers. If you want to validate the sum of these three fields you have to create a class-level constraint as you suggest. In this way your custom annotation is applied to the class not to fields so, how can you define groups on fields?

Instead, you may use something like this:

@Sum(min = 250, fields = {"length", "width", "height"})
public class MyClass {
    private String type;
    private String code;
    private int length;
    private int width;
    private int height;
        ...
}
like image 57
Alf Avatar answered Dec 08 '22 05:12

Alf