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

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

e7d9dc715bd233f8f93c01d33947c1f6.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 {

@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就可以验证了

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java 中编写自定义校验注解时,可以使用 `@ReportAsSingleViolation` 注解来指定只要有一个校验失败就返回结果,而不是等待所有的校验结果返回。同时,可以使用 `@javax.validation.constraints.Null` 和 `@javax.validation.constraints.NotNull` 注解来判断参数是否为 `null`。 具体来说,你可以按照以下步骤编写一个允许参数为空的自定义校验注解: 1. 定义注解 ```java @Target({ElementType.FIELD, ElementType.PARAMETER}) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = {MyValidator.class}) @ReportAsSingleViolation public @interface MyAnnotation { String message() default "my message"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; } ``` 2. 定义校验 ```java public class MyValidator implements ConstraintValidator<MyAnnotation, String> { @Override public boolean isValid(String value, ConstraintValidatorContext context) { if (value == null) { // 允许参数为空,直接返回 true return true; } // 对非空参数进行校验 boolean isValid = // 校验逻辑 if (!isValid) { context.disableDefaultConstraintViolation(); context.buildConstraintViolationWithTemplate("my message") .addConstraintViolation(); } return isValid; } } ``` 在校验中,我们首先判断参数是否为 `null`,如果是,则直接返回 `true`,即认为校验通过。如果参数不为 `null`,则进行校验逻辑,如果校验失败,则使用 `context.buildConstraintViolationWithTemplate()` 方法构建校验失败的信息。 3. 在需要校验参数上应用注解 ```java public void myMethod(@MyAnnotation String param) { // 方法逻辑 } ``` 在需要校验参数上使用 `@MyAnnotation` 注解,即可触发自定义校验注解校验逻辑。如果参数为 `null`,则直接返回 `true`,否则进行校验逻辑。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值