Skip to content

Instantly share code, notes, and snippets.

@ShigeoTejima
Created September 16, 2015 05:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ShigeoTejima/e857ede59ad1be667241 to your computer and use it in GitHub Desktop.
Save ShigeoTejima/e857ede59ad1be667241 to your computer and use it in GitHub Desktop.
spring boot correlation validation example - EitherRequired
package com.example.web;
import com.example.validation.EitherRequired;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@EitherRequired(fields = {"input", "otherInput"})
public class DemoForm {
private String input;
private String otherInput;
}
package com.example.validation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
@Documented
@Constraint(validatedBy = {EitherRequiredValidator.class})
@Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface EitherRequired {
String message() default "{com.example.validation.EitherRequired.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
String[] fields();
@Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface List {
EitherRequired[] value();
}
}
package com.example.validation;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
public class EitherRequiredValidator implements ConstraintValidator<EitherRequired, Object>{
private String[] fields;
private String message;
@Override
public void initialize(EitherRequired eitherRequired) {
fields = eitherRequired.fields();
message = eitherRequired.message();
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
BeanWrapper beanWrapper = new BeanWrapperImpl(value);
for (String field : fields) {
Object fieldValue = beanWrapper.getPropertyValue(field);
if (fieldValue != null) {
if (fieldValue instanceof String) {
if (!((String)fieldValue).isEmpty()) {
return true;
}
} else {
return true;
}
}
}
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate(message)
.addPropertyNode(fields[0]).addConstraintViolation();
return false;
}
}
Reference URL:
https://terasolunaorg.github.io/guideline/public_review/ArchitectureInDetail/Validation.html#id11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment