如何使用不带@Valid的注释来验证模型

问题描述 投票:0回答:1

在我的程序中,我接受一个包含电话号码的文件,我对其进行处理并将其添加到数据库中。我只能在方法参数中使用@Valid注解,但是如何在模型字段中使用注解呢?

下面的方法获取已收到的电话号码列表并将其转换为 NotifyUser 服务:

private NotificationResult convertStringToNotifyUser(List<String> records){
    List<NotifyUser> correctPhoneNumbers = new ArrayList<>();
    List<BadPhoneNumber> badPhoneNumbers = new ArrayList<>();
    for(String record: records){
        NotifyUser notifyUser = new NotifyUser();
        notifyUser.setPhone_number(record.trim());

        Errors errors = new BeanPropertyBindingResult(notifyUser, "notifyUser");
        notifyUserValidator.validate(notifyUser, errors);
        if(errors.hasErrors()){
            badPhoneNumbers.add(new BadPhoneNumber(record, errors.getFieldErrors()));
        }
        else {
            correctPhoneNumbers.add(notifyUser);
        }
    }
    return new NotificationResult(correctPhoneNumbers, badPhoneNumbers);
}

型号:

public class NotifyUser {
    @Id
    @Column(name = "phone_number")
    @NotEmpty(message = "Phone number cannot be empty")
    @Size(min = 11, max = 12, message = "the phone number can start with +7 or 8 and have 11 or 12 characters respectively")
    private String phone_number;

    //other code

我有一个想法,我可以手动编写与模型字段注释相同的验证逻辑,但那样我只会重复逻辑,这似乎不是一个好的做法。

java spring validation
1个回答
0
投票

尝试如下操作:

导入org.springframework.validation.Validator; 导入 javax.validation.ConstraintViolation;

@Autowired 私有 Validator 验证器;

设置违规 = validator.validate(notifyUser);

for(ConstraintViolation约束Violation:违规){ badPhoneNumbers.add(new BadPhoneNumber(record,constraintViolation.getMessage()));}

这是一个 Spring 验证器,它调用要针对模型对象进行验证的注释

© www.soinside.com 2019 - 2024. All rights reserved.