Skip to content

Instantly share code, notes, and snippets.

@raylax
Last active May 12, 2020 01:38
Show Gist options
  • Save raylax/b7122c29c6f4bac87d2077ecb8b469e7 to your computer and use it in GitHub Desktop.
Save raylax/b7122c29c6f4bac87d2077ecb8b469e7 to your computer and use it in GitHub Desktop.
package validator;
import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static validator.NullableLength.*;
import static validator.NullableLength.StringValidator;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* 可以为null,如果不为null必须满足(min <= len <= max)条件
*/
@Constraint(validatedBy = {StringValidator.class})
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
@Repeatable(List.class)
public @interface NullableLength {
/**
* 默认不对下限做校验
* 检查空请用
* {@link javax.validation.constraints.NotBlank}
* {@link javax.validation.constraints.NotEmpty}
* 相关注解
*/
int min() default -1;
int max() default Integer.MAX_VALUE;
/**
* 是否trim后进行判断
* 如果trim=true,请确认是否和
* {@link javax.validation.constraints.NotBlank}
* {@link javax.validation.constraints.NotEmpty}
* 等注解重复
*/
boolean trim() default false;
String message() default "{validator.NullableLength.message}";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
class StringValidator implements ConstraintValidator<NullableLength, String> {
private NullableLength annotation;
@Override
public void initialize(NullableLength annotation) {
this.annotation = annotation;
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if (value == null) {
return true;
}
int len = annotation.trim()
? value.trim().length()
: value.length();
return len >= annotation.min() && len <= annotation.max();
}
}
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
@Documented
@interface List {
NullableLength[] value();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment