自定义参数校验注解 (实现ConstraintValidator方法)

Hibernate Validator常用注解(图网上找的)

常ç¨æ³¨è§£.png

2.自定义校验器

    a.注解类

@Target({FIELD, METHOD, PARAMETER, ANNOTATION_TYPE})
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = PasswordValidator.class)
public @interface Password {

    /**
     * 默认错误消息
     *
     * @return
     */
    String message() default "密码过于简单";

    /**
     * 分组
     *
     * @return
     */
    Class<?>[] groups() default {};

    /**
     * 负载
     *
     * @return
     */
    Class<? extends Payload>[] payload() default {};

    /**
     * 指定多个时使用
     */
    @Target({FIELD, METHOD, PARAMETER, ANNOTATION_TYPE})
    @Retention(RUNTIME)
    @Documented
    @interface List {
        Password[] value();
    }
}

b.验证器

public class PasswordValidator implements ConstraintValidator<Password, String> {

    @Override
    public void initialize(Password constraintAnnotation) {
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        return StringUtils.isEmpty(value) || ValidateUtils.validatePassword(value);
    }
}c

c.校验工具类

/**
 * 校验工具类
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class ValidateUtils {
    
    public static final String[] IMG_FILE_TYPE = {".png", ".jpg"};
    public static final Pattern ipPattern = Pattern.compile("\\d{1,3}(\\.\\d{1,3}){3}");
    public static final Pattern usernamePattern = Pattern.compile("(?!_)\\w{6,32}");
    public static final Pattern passwordPattern = Pattern.compile("(?![0-9]+$)(?![a-zA-Z]+$)(?!(![0-9A-Za-z])+$)\\S{6,32}");
    public static final Pattern mobilePattern = Pattern.compile("1\\d{10}");
    public static final Pattern phonePattern = Pattern.compile("^([0,4]{1}[0-9]{2,3}\\-)?([1-9][0-9]{6,7})$");
    public static final Pattern codePattern = Pattern.compile("(?!_)\\w{1,64}");

    /**
     * 校验图片是否符合规则,通过返回true,不通过返回false
     * @param fileName 图片名称
     * @return 通过返回true,不通过返回false
     */
    public static boolean validateImageFile(String fileName) {
        for (String string : IMG_FILE_TYPE) {
            if (fileName.endsWith(string)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 校验图片
     * @param fileName    图片名称
     * @param inputStream 图片文件流
     * @return 通过返回true,不通过返回false
     */
    public static boolean validateImageFile(String fileName, InputStream inputStream) {
        if (!validateImageFile(fileName)) {
            return false;
        }

        BufferedImage bufReader;
        try {
            bufReader = ImageIO.read(inputStream);
        } catch (IOException e) {
            throw new CoreException("Failed to read input stream", e);
        }

        int width = bufReader.getWidth();
        int height = bufReader.getHeight();
        return !(width == 0 || height == 0);
    }

    /**
     * 校验IP
     *
     * @param ip IP地址
     * @return 通过返回true,不通过返回false
     */
    public static boolean validateIp(String ip) {
        return ipPattern.matcher(ip).matches();
    }

    /**
     * 校验用户名
     *
     * @param username 用户名
     * @return 通过返回true,不通过返回false
     */
    public static boolean validateUsername(String username) {
        return usernamePattern.matcher(username).matches();
    }

    /**
     * 校验密码
     *
     * @param password 密码
     * @return 通过返回true,不通过返回false
     */
    public static boolean validatePassword(String password) {
        return passwordPattern.matcher(password).matches();
    }

    /**
     * 校验手机号码
     *
     * @param mobile 手机号码and固话(满足其一)
     * @return 通过返回true,不通过返回false
     */
    public static boolean validateMobile(String mobile) {
       if(!((mobile.length() == 11 && mobilePattern.matcher(mobile).matches())
             ||(mobile.length() < 16&& phonePattern.matcher(mobile).matches()))){
          return false;
       }else{
          return true;
       }
        //return mobilePattern.matcher(mobile).matches();
    }


    /**
     * @Description 校验电话号码是否是手机号码
     * @Author xj
     * @Date 10:08 2018/8/29
     * @Param [mobile]
     * @return 通过返回true,不通过返回false
     **/
    public static boolean validatePhone(String mobile) {
        if(mobile.length() == 11 && mobilePattern.matcher(mobile).matches()){
            return true;
        }else{
            return false;
        }

    }

    /**
     * 校验编号
     *
     * @param code 编号
     * @return 通过返回true,不通过返回false
     */
    public static boolean validateCode(String code) {
        return codePattern.matcher(code).matches();
    }

    private static final String ATOM = "[a-z0-9!#$%&'*+/=?^_`{|}~-]";
    private static final String DOMAIN = ATOM + "+(\\." + ATOM + "+)*";
    private static final String IP_DOMAIN = "\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\]";
    private static final int MAX_LOCAL_PART_LENGTH = 64;
    private static final int MAX_DOMAIN_PART_LENGTH = 255;

    /**
     * Regular expression for the local part of an email address (everything before '@')
     */
    private static final Pattern localPattern = Pattern.compile(
            ATOM + "+(\\." + ATOM + "+)*", CASE_INSENSITIVE
    );

    /**
     * Regular expression for the domain part of an email address (everything after '@')
     */
    private static final Pattern domainPattern = Pattern.compile(
            DOMAIN + "|" + IP_DOMAIN, CASE_INSENSITIVE
    );

    private static String toAscii(String unicodeString) throws IllegalArgumentException {
        String asciiString = "";
        int start = 0;
        int end = unicodeString.length() <= 63 ? unicodeString.length() : 63;
        while (true) {
            asciiString += IDN.toASCII(unicodeString.substring(start, end));
            if (end == unicodeString.length()) {
                break;
            }
            start = end;
            end = start + 63 > unicodeString.length() ? unicodeString.length() : start + 63;
        }
        return asciiString;
    }

    private static boolean matchPart(String part, Pattern pattern, int maxLength) {
        String asciiString;
        try {
            asciiString = toAscii(part);
        } catch (IllegalArgumentException e) {
            return false;
        }
        if (asciiString.length() > maxLength) {
            return false;
        }
        Matcher matcher = pattern.matcher(asciiString);
        return matcher.matches();
    }

    /**
     * 验证邮箱
     *
     * @param value 邮箱
     * @return 验证结果
     */
    public static boolean validateEmail(String value) {
        String[] emailParts = value.toString().split("@", 3);
        if (emailParts.length != 2) {
            return false;
        }
        if (emailParts[0].endsWith(".") || emailParts[1].endsWith(".")) {
            return false;
        }
        if (!matchPart(emailParts[0], localPattern, MAX_LOCAL_PART_LENGTH)) {
            return false;
        }
        return matchPart(emailParts[1], domainPattern, MAX_DOMAIN_PART_LENGTH);
    }

    public static final Pattern openIdPattern = Pattern.compile("(?!_)(\\w|-){1,64}");

    /**
     * 验证open id
     *
     * @param value open id
     * @return 验证结果
     */
    public static boolean validateOpenId(String value) {
        return openIdPattern.matcher(value).matches();
    }

}

d.在需要的实体类上加上@Password就可以验证了

转载于:https://my.oschina.net/pjpj/blog/2989540

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值