已编辑
要验证子电子邮件列表,您可以创建自定义验证。
我编写了一个自定义验证如下
1-创建名为 ChildEmailValidation 的注释
@Documented
@Constraint(validatedBy = ChildEmailValidator.class)
@Target( { ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface ChildEmailValidation {
String message() default "Duplicate Email";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
2-为ChildEmailValidation
在这部分,您可以编写您的自定义业务进行验证。(你可以写你的算法)
public class ChildEmailValidator implements ConstraintValidator<ChildEmailValidation, List<Child>> {
@Override
public void initialize(ChildEmailValidation constraintAnnotation) {
}
@Override
public boolean isValid(List<Child> childList, ConstraintValidatorContext constraintValidatorContext) {
//Create empty mailList
List<String> mailList = new ArrayList<>();
//Iterate on childList
childList.forEach(child -> {
//Checks if the mailList has the child's email
if (mailList.contains(child.getMail())) {
//Found Duplicate email
throw new DuplicateEmailException();
}
//Add the child's email to mailList (If duplicate email is not found)
mailList.add(child.getMail());
});
//There is no duplicate email
return true;
}
}
3-添加@ChildEmailValidation
父亲类
public class Father {
List<Child> child;
@ChildEmailValidation
public List<Child> getChild() {
return child;
}
public void setChild(List<Child> child) {
this.child = child;
}
}
4-@Valid
放入fatherDto
控制器
@RestController
@RequestMapping(value = "/test/", method = RequestMethod.POST)
public class TestController {
@RequestMapping(value = "/test")
public GenericResponse getFamily(@RequestBody @Valid Father fatherDto) {
// ...
}
}