Issue
So I have a class and a field that is list of strings and I want to validate every one of them, but it's not working, I tried this and this didn't work out:
public class Info {
@NotNull
@NotEmpty
private List<@Email(message = "uncorrect email") String> emails;
}
I also tried this and it didn't work:
public class Info {
@NotNull
@NotEmpty
private @Valid List<@Email(message = "uncorrect email") String> emails;
}
But when it's just one String it works fine.
public class Info {
@NotNull
@NotEmpty
private @Email(message = "uncorrect email") String email;
}
How can I achieve what I want?
Solution
Latest versions of hibernate validator support it. You can go with the following changes to achieve the desired validation behaviour.
<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 + "]";
}
}
Adding the @Valid
@PostMapping("/post")
public void post(@RequestBody @Valid Info info) {
System.out.println(info);
}
Answered By - B.S
Answer Checked By - Pedro (JavaFixing Volunteer)