You can enforce a subset of constraints using validation groups using groups
on api:validation.Validated[]. More information is available in the Bean Validation specification
snippet::io.micronaut.docs.datavalidation.groups.FinalValidation[tags="clazz", indent=0]
-
Define a custom validation group. This one extends
Default
so any validations done with this group will include constraints in theDefault
group.
snippet::io.micronaut.docs.datavalidation.groups.Email[tags="clazz", indent=0]
-
Specify a constraint using the Default validation group. This constraint will only be enforced when
Default
is active. -
Specify a constraint using the custom
FinalValidation
validation group. This constraint will only be enforced whenFinalValidation
is active.
Annotate your controller with api:validation.Validated[], specifying the validation groups that will be active or letting it default to Default
. Also annotate the binding POJO with @Valid
.
snippet::io.micronaut.docs.datavalidation.groups.EmailController[tags="imports,clazz", indent=0,title="Example"]
-
Annotating with api:validation.Validated[] without specifying groups means that the
Default
group will be active. Since this is defined on the class, it will apply to all methods. -
Constraints in the
Default
validation group will be enforced, inheriting from the class. The effect is that@NotBlank
onemail.recipient
will not be enforced when this method is called. -
Specifying
groups
means that these validation groups will be enforced when this method is called. Note thatFinalValidation
extendsDefault
so constraints from both groups will be enforced. -
Constraints in the
Default
andFinalValidation
validation groups will be enforced, sinceFinalValidation
extendsDefault
. The effect is that both@NotBlank
constraints inemail
will be enforced when this method is called.
Validation of POJOs using the default validation group is shown in the following test:
snippet::io.micronaut.docs.datavalidation.groups.EmailControllerSpec[tags="pojovalidateddefault",indent=0]
Validation of POJOs using the custom FinalValidation
validation group is shown in the following test:
snippet::io.micronaut.docs.datavalidation.groups.EmailControllerSpec[tags="pojovalidatedfinal",indent=0]