Files
utils/src/main/java/com/hua/valid/ConditionValidateImpl.java
2024-07-20 14:34:56 +08:00

70 lines
2.4 KiB
Java

package com.hua.valid;
import cn.hutool.core.util.ReflectUtil;
import com.hua.valid.annotation.ValidPlus;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Valid;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.List;
/**
* @author Hua
* @since 2024/7/18 下午2:43
*/
public class ConditionValidateImpl implements ConstraintValidator<ValidPlus, Object> {
@Override
public void initialize(ValidPlus constraintAnnotation) {
}
@Override
public boolean isValid(Object o, ConstraintValidatorContext constraintValidatorContext) {
ErrorMessage errorMessage = new ErrorMessage();
validObj(o, errorMessage, o);
if(errorMessage.isError()) {
constraintValidatorContext.disableDefaultConstraintViolation();
constraintValidatorContext.buildConstraintViolationWithTemplate(errorMessage.getErrorMessage()).addConstraintViolation();
return false;
}
return true;
}
private void validObj(Object o, ErrorMessage errorMessage, Object originObj) {
if (o instanceof List<?> list) {
for (Object obj : list) {
validObj(obj, errorMessage,originObj);
}
return;
}
Field[] fields = ReflectUtil.getFields(o.getClass());
for (Field field : fields) {
Valid annotation = field.getAnnotation(Valid.class);
if (annotation != null) {
validObj(ReflectUtil.getFieldValue(o,field),errorMessage, originObj);
}
Annotation[] annotations = field.getAnnotations();
if (annotations == null || annotations.length == 0) {
continue;
}
Object fieldValue = ReflectUtil.getFieldValue(o, field);
Annotation formatAnnotation = field.getAnnotation(ValidPlus.class);
if (formatAnnotation == null) {
throw new RuntimeException("Format annotation is missing on the field.");
}
HandleDTO handleDTO = new HandleDTO.HandleDTOBuilder().setOriginObj(originObj)
.setAnnotations(annotations)
.setAnnotations(annotations)
.setField(field)
.setErrorMessage(errorMessage)
.setFieldValue(fieldValue).build();
AnnotationHandleFactory.handle(handleDTO);
}
}
}