Skip to content

Instantly share code, notes, and snippets.

@arahansa
Last active July 26, 2016 19:38
Show Gist options
  • Save arahansa/2aff10078346c30c94aa2cbd16b66787 to your computer and use it in GitHub Desktop.
Save arahansa/2aff10078346c30c94aa2cbd16b66787 to your computer and use it in GitHub Desktop.
커스텀 밸리데이션
@PasswordsNotEqual(
passwordFieldName = "password",
passwordVerificationFieldName = "passwordVerification"
)
@Target( { TYPE, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = PasswordsNotEmptyValidator.class)
@Documented
public @interface NickNameNotEmpty {
String message() default "PasswordsNotEmpty";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
String userFieldName() default "";
String anonymousNickFieldName() default "";
}
import org.apache.commons.lang3.StringUtils;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class NickNameNotEmptyValidator implements ConstraintValidator<NickNameNotEmpty, Object> {
private String userFieldName;
private String anonymousNickFieldName;
@Override
public void initialize(NickNameNotEmpty constraintAnnotation) {
this.userFieldName = constraintAnnotation.userFieldName();
this.anonymousNickFieldName = constraintAnnotation.anonymousNickFieldName();
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
context.disableDefaultConstraintViolation();
try {
User user = (User) ValidatorUtil.getFieldValue(value, userFieldName);
if(user!=null) return true;
String anonNick = (String) ValidatorUtil.getFieldValue(value, anonymousNickFieldName);
if (StringUtils.isBlank(anonNick)) {
ValidatorUtil.addValidationError(anonymousNickFieldName, context);
return false;
}
}
catch (Exception ex) {
throw new RuntimeException("Exception occurred during validation", ex);
}
return true;
}
}
/**
* @author Petri Kainulainen
*/
public class ValidatorUtil {
public static void addValidationError(String field, ConstraintValidatorContext context) {
context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate())
.addNode(field)
.addConstraintViolation();
}
public static Object getFieldValue(Object object, String fieldName) throws NoSuchFieldException, IllegalAccessException {
Field f = object.getClass().getDeclaredField(fieldName);
f.setAccessible(true);
return f.get(object);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment