新增自定义校验
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
package com.ycjy.dao;
|
||||
|
||||
import com.ycjy.validation.NoSensitive;
|
||||
import jakarta.validation.constraints.*;
|
||||
|
||||
public class User {
|
||||
@@ -11,6 +12,7 @@ public class User {
|
||||
@NotBlank(message = "name not null")
|
||||
@NotBlank // 非空
|
||||
@Size(min = 1, max = 5, message = "name long 1~5") // 长度区间(包含)
|
||||
@NoSensitive
|
||||
private String name;
|
||||
|
||||
@Min(value = 1, message = "age notmin 0")
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.ycjy.validation;
|
||||
|
||||
import jakarta.validation.Constraint;
|
||||
import jakarta.validation.Payload;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Target({ElementType.FIELD, ElementType.PARAMETER})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Constraint(validatedBy = NoSensitiveValidator.class)
|
||||
public @interface NoSensitive {
|
||||
String message() default "bao han min gan===="; // 校验失败提示
|
||||
Class<?>[] groups() default {}; // 分组,固定写
|
||||
Class<? extends Payload>[] payload() default {}; // 固定写
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.ycjy.validation;
|
||||
|
||||
import jakarta.validation.ConstraintValidator;
|
||||
import jakarta.validation.ConstraintValidatorContext;
|
||||
|
||||
public class NoSensitiveValidator implements ConstraintValidator<NoSensitive, String> {
|
||||
@Override
|
||||
public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
|
||||
if (s == null) {
|
||||
return true; // null 交给 @NotNull 管
|
||||
}
|
||||
return !s.contains("nm");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user