gpt4 book ai didi

java - 如何加入多个验证注解

转载 作者:行者123 更新时间:2023-12-03 08:32:44 28 4
gpt4 key购买 nike

我有以下注释来验证密码:

@Target({FIELD})
@Retention(RUNTIME)
@Documented
@NotNull
@Length(min = 8, max = 32)
@Pattern(regexp = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])(?=\\S+$).{8,}$")
public @interface Password {
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}

但是 spring 验证不识别这个规则。我将此注释用作:

@Password
private String password;

如何在不定义 ConstraintValidator 实例的情况下获取它?

最佳答案

如果你想使用ConstraintValidator,你可以这样做:

创建密码注释:

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

String message() default "{propertyPath} is not a valid password";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};

}

然后创建PasswordConstraintValidator类:

public class PasswordConstraintValidator implements ConstraintValidator<Password, String> {

private final String PASSWORD_PATTERN =
"^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#&()–[{}]:;',?/*~$^+=<>]).{8,20}$";

private final Pattern pattern = Pattern.compile(PASSWORD_PATTERN);

@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if(Objects.isNull(value)) {
return false;
}
if((value.length() < 8) || (value.length() > 32)) {
return false;
}
if(!pattern.matcher(password).matches()){
return false;
}

}

然后将其应用到您的字段之一,请注意,您还可以添加自定义消息:

@Password(message = "....")
private String password;

@Password
private String passwd;

您还可以用适当的方法重构每个 if 语句(以获得干净的代码):如下所示:

  @Override
public boolean isValid(String value, ConstraintValidatorContext context) {
return (notNull(value) && isValidPasswordLength(value) && isValidPasswordValue(value));
}

更新

由于您不想使用 ConstraintValidator,因此您的实现看起来不错,您只需在模型上添加 @Valid 即可执行级联验证并包含 spring-boot-starter-validation 以确保包含验证 api,并在自定义注释上添加 @Constraint(validatedBy = {})。这是一个 groovy 示例(您可以使用 spring CLI 运行它):

@Grab('spring-boot-starter-validation')

@Grab('lombok')
import lombok.*

@Grab('javax.validation:validation-api:2.0.1.Final')
import javax.validation.constraints.NotNull
import javax.validation.constraints.Size
import javax.validation.Valid
import javax.validation.Constraint
import javax.validation.Payload

import java.lang.annotation.Documented
import java.lang.annotation.Target
import java.lang.annotation.Retention

import static java.lang.annotation.ElementType.FIELD
import static java.lang.annotation.RetentionPolicy.RUNTIME

@RestController
class TestCompositeAnnotation {

@PostMapping(value = "/register", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public String register(@Valid @RequestBody User user) {
return "password " + user.password + " is valid";
}
}

class User {
public String username;
@Password
public String password;
}

@Target(value = FIELD)
@Retention(RUNTIME)
@Documented
@NotNull
@Constraint(validatedBy = []) // [] is for groovy make sure to replace is with {}
@Size(min = 8, max = 32)
@interface Password {
String message() default "invalid password";

Class<?>[] groups() default []; // [] is for groovy make sure to replace is with {}

Class<? extends Payload>[] payload() default []; // [] is for groovy make sure to replace is with {}
}

所以当你 curl 时:

curl -X POST http://localhost:8080/register -d '{"username": "rsone", "password": "pa3"}' -H "Content-Type: application/json"

您将收到错误验证响应:

{"timestamp":"2020-11-07T16:43:51.926+00:00","status":400,"error":"Bad Request","message":"...","path":"/register"}

关于java - 如何加入多个验证注解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64727153/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com