Summarize the method (correlation check) of comparing multiple items with Spring Boot and performing validation.
First, the entity class that receives the date input from the user.
package com.sample.Form;
import com.sample.Annotation.DayCheck;
import lombok.Data;
import javax.validation.constraints.NotNull;
import java.time.LocalDate;
@Data
@DayCheck //(1)
public class SearchLogForm {
@NotNull(message = "Please put the date^^") //(2)
private LocalDate startDate;
@NotNull(message = "Please put the date^^")
private LocalDate endDate;
}
Commentary (1)-> Add your own annotation to be created later to the whole class. (2)-> Since it is meaningless if the date is not entered in the first place, @NotNull annotation is added so as not to allow Null.
Next, the annotation class to be given to the entity.
package com.sample.Annotation;
import com.sample.Validation.DayCheckValidation;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;
@Documented
@Constraint(validatedBy = DayCheckValidation.class) //(1)
@Target(ElementType.TYPE) //(2)
@Retention(RetentionPolicy.RUNTIME)
public @interface DayCheck {
String message() default "Enter the end date after the start date^^";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
Commentary (1)-> Specify the validation check class to be created later. (2)-> When validating multiple items, specify TYPE because it is given to the class itself.
Finally, create a validation check class.
package com.sample.Validation;
import com.sample.Annotation.DayCheck;
import com.sample.Form.SearchLogForm;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class DayCheckValidation implements ConstraintValidator<DayCheck, SearchLogForm> { //(1)
@Override
public boolean isValid(SearchLogForm value, ConstraintValidatorContext context) {
if (value.getStartDate() == null || value.getEndDate() == null) { //(2)
return false;
}
return value.getStartDate().isBefore(value.getEndDate()) ? true : false; //(3)
}
}
Commentary (1)-> In <> of Constraint Validator, specify the entity class to annotate (check) the annotation created above before the comma and after it. (2)-> If the date is null, a nullpo will occur, so check for null. (3)-> Compare dates. Implemented to return false if the end date is before the start date and true if it is later.
If you set the start date to a date before the end date ...
I was able to check it properly.
・ Https://terasolunaorg.github.io/guideline/public_review/ArchitectureInDetail/Validation.html#validation-correlation-check ・ Https://itneko.com/kotlin-validate-correlation/
Recommended Posts