我想做一个密码验证器,其中密码应该至少有1个大写,1个小写和1个特殊,没有空格。我通过 Postman 密码“123”,我得到了Http 200. OK,但我不应该,因为它违反了我的密码验证器。下面是我的代码:Dto请求:
@Data
@AllArgsConstructor
public class UserRegistrationDtoRequest {
@NotNull
private String email;
@ValidPassword
private String password;
private String address;
}
字符串
有效密码注解:
@Documented
@Constraint(validatedBy = PasswordConstraintValidator.class)
@Target({ElementType.TYPE,ElementType.FIELD,ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ValidPassword {
String message() default "Invalid password.Password should have at least 8 characters";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
型
ConstraintValidator实现:
public class PasswordConstraintValidator implements ConstraintValidator<ValidPassword,String> {
@Override
public void initialize(ValidPassword constraintAnnotation) {
ConstraintValidator.super.initialize(constraintAnnotation);
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
PasswordValidator validator = new PasswordValidator(Arrays.asList(
new LengthRule(8,20),
new CharacterRule(EnglishCharacterData.UpperCase,1),
new CharacterRule(EnglishCharacterData.LowerCase,5),
new CharacterRule(EnglishCharacterData.Special,1),
new WhitespaceRule()));
RuleResult ruleResult = validator.validate(new PasswordData(value));
if(ruleResult.isValid()){
return true;
}
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate(
validator.getMessages(ruleResult).toString()).addConstraintViolation();
return false;
}
}
型
1条答案
按热度按时间vpfxa7rd1#
Sping Boot 验证使用javax提供的@Valid注解。
字符串