In BeanValidation
, I will summarize the method of correlation check within the range where you do not create your own annotation (& complete within the object to be validated).
See the official documentation for technical details.
As a rule of thumb, if you want to perform a process like "matching the data passed from the front and the data acquired from the DB, validating it, and registering it in the DB if it is a valid", I feel that it is better to separate it as follows. I will.
In this article, I will write about 2 in particular, but since this process is closely related to the data structure of the validation result (especially in Bean Validation
, the field name and method name affect the data returned to the front), write them together. If this happens, changes in 2 and the front will spread to 1, and changes in 1 and 3 will spread to the front.
Because I wrote 1 to 3 together, I feel very painful because "I can't stand here when I try to change that ...".
I will introduce the following three roughly.
--Use ʻAssertTrue or ʻAssertFalse
for the function
--Annotate getters
--Application
--Prepare a field to store the correlation check result
or ʻAssertFalse
in the functionThis is a commonly introduced method for correlation check.
If the method name is ʻisValid, the property name of the error will be
valid`.
@AssertTrue
private boolean isValid() {
/*Correlation check*/
}
Note that the return value must be the primitive type boolean
when performing a correlation check with the method name ʻis ~`. Is required.
In Bean Validation
, validation can be done by annotating the field, but validation can also be done by annotating the method (= getter) namedget ~
.
In other words, you can check the correlation even within the getter.
@AssertTrue
@NotNull
private Boolean getValid() {
/*Correlation check*/
}
When performing a correlation check using a getter, the return value can be anything.
In other words, you can say "Error 1 if the return value is null
, Error 2, if it is 1 or more, ... ".
In the example I wrote earlier, validation is done like " Not Null
for null
, ʻAssert True for not
true` ".
This makes it possible to separate error messages for each error without changing properties.
So far, we have introduced the correlation check by annotating the function, but if you store the value in the field at the time of initialization, you can also check the correlation by annotating it.