Spring Boot 列表内的Javax验证

nuypyhwy  于 2022-11-05  发布在  Spring
关注(0)|答案(1)|浏览(157)

我有一个类和一个字符串列表字段,我想验证每一个字符串,但是没有用,我试过了,但是没有用:

public class Info {
@NotNull
@NotEmpty
private List<@Email(message = "uncorrect email") String> emails;
}

我也试过这个,但没有效果:

public class Info {
@NotNull
@NotEmpty
private @Valid List<@Email(message = "uncorrect email") String> emails;
}

但是当它只有一个字符串时,它工作得很好。

public class Info {
@NotNull
@NotEmpty
private @Email(message = "uncorrect email") String email;
}

我怎样才能实现我的愿望?

esyap4oy

esyap4oy1#

最新版本的hibvalidator支持它,你可以通过以下的修改来实现你想要的验证行为。

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <version>2.7.0</version>
    </dependency>
    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
        <version>2.0.1.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>6.0.13.Final</version>
    </dependency>
</dependencies>

Java Bean

import java.util.List;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;

public class Info {

    @NotNull
    @NotEmpty
    private List<@Email(message = "List contain atleast one incorrect email") String> emails;

    @NotNull
    @NotEmpty
    @Email(message = "incorrect email")
    private String email;

    public List<String> getEmails() {
        return emails;
    }

    public void setEmails(List<String> emails) {
        this.emails = emails;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "Info [emails=" + emails + ", email=" + email + "]";
    }

}

添加@Valid

@PostMapping("/post")
public void post(@RequestBody @Valid Info info) {
    System.out.println(info);
}

相关问题