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.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Constraint(validatedBy = CheckLengthFetureValidator.class)
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface CheckLengthFeture {

    int minLength() default 0;

    int maxLength() default 0;

    int strictLength() default 0;

    boolean required() default false;

    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;

public class CheckLengthFetureValidator implements ConstraintValidator<CheckLengthFeture, String> {

    private int minLength;

    private int maxLength;

    private int strictLength;

    private boolean required;

    @Override
    public void initialize(CheckLengthFeture feture) {
        this.minLength = feture.minLength();
        this.maxLength = feture.maxLength();
        this.strictLength = feture.strictLength();
        this.required = feture.required();
    }

    @Override
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
        if (StringUtils.isNotBlank(s)) {
            if ((minLength != 0 || maxLength != 0) && strictLength != 0) {
                return false;
            } else {
                if (minLength != 0 && maxLength == 0) {
                    return CommonUtil.strlen(s) >= minLength ? true : false;
                } else if (minLength == 0 && maxLength != 0) {
                    return CommonUtil.strlen(s) <= maxLength ? true : false;
                } else if (minLength != 0 && maxLength != 0) {
                    return CommonUtil.strlen(s) >= minLength && CommonUtil.strlen(s) <= maxLength ? true : false;
                } else if (strictLength != 0) {
                    return CommonUtil.strlen(s) == strictLength ? true : false;
                } else {
                    return false;
                }
            }
        } else {
            if (required) {
                return false;
            } else {
                return true;
            }
        }
    }
}
View Code
复制代码
复制代码
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

@Slf4j
public class CommonUtil {
    private static final Logger logger = LoggerFactory.getLogger(CommonUtil.class);
    private static Random random = new Random();

    public static String getUUID() {
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        return uuid;
    }

    /**
     * 将String的List泛型转换成以;号分隔的字符串
     *
     * @param stringList
     * @return
     */
    public static String transListToStr(List<String> stringList) {
        if (stringList != null && stringList.size() > 0) {
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append("");
            Iterator<String> stringIterator = stringList.iterator();
            while (stringIterator.hasNext()) {
                stringBuffer.append(stringIterator.next());
                if (stringIterator.hasNext()) {
                    stringBuffer.append(";");
                }
            }
            return stringBuffer.toString();
        } else {
            return null;
        }
    }

    /**
     * 将字符串以split分隔,并且添加到List中
     *
     * @param str
     * @param split
     * @return
     */
    public static List<String> transStrToList(String str, String split) {
        if (StringUtils.isNotBlank(str)) {
            String[] strings = str.split(split);
            List<String> stringList = new ArrayList<>();
            for (String string : strings) {
                stringList.add(string);
            }
            return stringList;
        } else {
            return null;
        }
    }

    /**
     * 判断字符串长度,当为汉字时,以2个字节计算
     *
     * @param str
     * @return
     */
    public static int strlen(String str) {
        int len = 0;
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
                len++;
            } else {
                len += 2;
            }
        }
        return len;
    }

}
View Code
复制代码
复制代码
@CheckLengthFeture(maxLength = 6, required = true, message = "")
    private String xxx;
    @CheckLengthFeture(required = true, message = "")
    private String xxx;
View Code
复制代码

 

 

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

posted on   Hi,ZHF  阅读(11)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
历史上的今天:
2019-07-01 webhook功能概述
2019-07-01 metabase运行
点击右上角即可分享
微信分享提示