zhihuifan

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  83 随笔 :: 0 文章 :: 4 评论 :: 17万 阅读
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

引入依赖:

复制代码
<!--jsr 303-->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>

<!-- hibernate validator-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.0.Final</version>
</dependency>
View Code
复制代码

自定义校验注释:

复制代码
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;

/**
 * 检查是否属于指定的值
 * 例:@TargetValue(values="00,01,02,03,04,05,06,08,13",message="证件类型不正确") 
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER,ElementType.FIELD})
@Constraint(validatedBy = TargetValueValidator.class)
public @interface TargetValue {
    
    //指定的值,多个用,隔开
    String values();
    
    //指定提示内容
    String message() default "";
    
    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

}
View Code
复制代码
复制代码
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * 注解@TargetValue实现
 */
public class TargetValueValidator implements ConstraintValidator<TargetValue, Object> {
    private String values;

    @Override
    public void initialize(TargetValue targetValue) {
        this.values = targetValue.values();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {

        //允许为空
        if (null == value || StringUtils.isBlank(value.toString())) {
            return true;
        }

        String[] valuesArr = values.split(",");
        if (valuesArr.length == 0) {
            return false;
        }

        for (String str : valuesArr) {
            if (str.equals(value)) {
                return true;
            }
        }

        return false;
    }

}
View Code
复制代码

 

声明:此博客为个人学习之用,如与其他作品雷同,纯属巧合,转载请指明出处!

posted on   Hi,ZHF  阅读(9)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示
历史上的今天:
2019-07-01 webhook功能概述
2019-07-01 metabase运行
点击右上角即可分享
微信分享提示