@Valid验证,页面提交没反应,很大原因是controller层的方法没使用@ResponseBody,使得BindingResult的数据无法通过JSON反馈给前台页面。验证成功后,可通过window.location.href来跳转页面。
限制 | 说明 |
---|---|
@Null | 限制只能为null |
@NotNull | 限制必须不为null |
@AssertFalse | 限制必须为false |
@AssertTrue | 限制必须为true |
@DecimalMax(value) | 限制必须为一个不大于指定值的数字 |
@DecimalMin(value) | 限制必须为一个不小于指定值的数字 |
@Digits(integer,fraction) | 限制必须为一个小数,且整数部分的位数不能超过integer,小数部分的位数不能超过fraction |
@Future | 限制必须是一个将来的日期 |
@Max(value) | 限制必须为一个不大于指定值的数字 |
@Min(value) | 限制必须为一个不小于指定值的数字 |
@Past | 限制必须是一个过去的日期 |
@Pattern(value) | 限制必须符合指定的正则表达式 |
@Size(max,min) | 限制字符长度必须在min到max之间 |
@Past | 验证注解的元素值(日期类型)比当前时间早 |
@NotEmpty | 验证注解的元素值不为null且不为空(字符串长度不为0、集合大小不为0) |
@NotBlank | 验证注解的元素值不为空(不为null、去除首位空格后长度为0),不同于@NotEmpty,@NotBlank只应用于字符串且在比较时会去除字符串的空格 |
验证注解的元素值是Email,也可以通过正则表达式和flag指定自定义的email格式 |
引用实例:
1、entity实体层
@NotEmpty(message="姓名不能为空!")
@Column(length=50)
private String name;
@NotNull(message="年龄不能为空!")
@Min(value=18,message="年龄必须大于18岁!")
@Column(length=50)
private Integer age;
2、控制层
@ResponseBody
@PostMapping(value="/add")
public String add(@Valid Student student,BindingResult bindingResult){
if(bindingResult.hasErrors()){
return bindingResult.getFieldError().getDefaultMessage();
}else{
studentService.add(student);
return "OK";
}
}
3、页面调用
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>添加页面</title>
<script src="jQuery.js"></script>
<script type="text/javascript">
function doSubmit(){
$.post("/student/add",{name:$("#name").val(),age:$("#age").val()},
if(result == "OK"){
alert("保存成功!")
window.location.href = "/book/list"; //通过JSON返回值判断跳转
}else {
alert(result);
}
);
}
</script>
</head>
<body>
姓名:<input type="text" id="name" name="name"/>
年龄:<input type="text" id="age" name="age"/>
<input type="button" value="提交" onclick="doSubmit()"/>
</body>
</html>