Springboot 自定义校验代码实例
人气:1这篇文章主要介绍了Springboot 自定义校验代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
StartWithValidation.class
@Documented @Constraint(validatedBy = StartWithValidator.class ) @Target({METHOD, FIELD}) @Retention(RUNTIME) public @interface StartWithValidation { String message() default "不是正确的性别取值范围"; String start() default "_"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; @Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER}) @Retention(RUNTIME) @Documented @interface List { StartWithValidation[] value(); } }
StartWithValidator.class
public class StartWithValidator implements ConstraintValidator<StartWithValidation, String> { private String start; @Override public void initialize(StartWithValidation constraintAnnotation) { start = constraintAnnotation.start(); } @Override public boolean isValid(String value, ConstraintValidatorContext context) { if (!StringUtils.isEmpty(value)) { return value.startsWith(start); } return true; } }
运用
@StartWithValidation(message = "Param 'address' must be start with 'Beijing'.", start = "Beijing") public String address;
解释:
地址必须以Beijing开头,否则校验失败
您可能感兴趣的文章:
加载全部内容