spring validate 验证List集合
演示用类User/Address
import lombok.Data;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Pattern;
import java.io.Serializable;
/**
* @Description: 地址
*
* @author lee
* @date 2020/7/16 9:28
*/
@Data
public class Address implements Serializable {
@NotEmpty
String detail;
@Pattern(regexp = "$[0-9]{6}$",message = "邮编格式不正确,邮政编码为6位数字")
String postCode;
}
import lombok.Data;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.List;
/**
* @Description: 用户
*
* @author lee
* @date 2020/7/16 9:27
*/
@Data
public class User implements Serializable {
@NotEmpty
String name;
@NotNull
Integer age;
/**
* 注意,如果不添加@Size(min = 1)则表示addresses可以为空,
* 添加后就必须至少有一个元素,需要验证List集合内的元素需要添加@Valid,参考
* @see javax.validation.Valid
* @see javax.validation.constraints.NotEmpty
*/
@Size(min = 1)
@Valid
List<Address> addresses;
}
校验controller
/***
* 验证测试
*
* @param user
* @return
*/
@PostMapping("/save")
public Object save(@RequestBody @Valid User user){
return "success";
}
运行调试结果:
已经完成List集合校验,并显示了验证错误信息。
原创文章,作者:kepupublish,如若转载,请注明出处:https://blog.ytso.com/243560.html