一.常用验证规则
@NotBlank: 判断字符串是否为 null 或者是空串(去掉首尾空格)。
@NotEmpty: 判断字符串是否 null 或者是空串。
@Length: 判断字符的长度(最大或者最小)
@Min: 判断数值最小值
@Max: 判断数值最大值
@Email: 判断邮箱是否合法
二.案例:新建项目:05-spt-form-check-01
1.pom文件:
<!-- springBoot的启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.0.1.RELEASE</version>
</dependency>
<!-- thymeleaf的启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.0.1.RELEASE</version>
</dependency>
2.后端代码:
package com.ljf.form.controller;
import com.ljf.form.model.Users;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.validation.Valid;
/**
* @ClassName: UsersController
* @Description: TODO
* @Author: liujianfu
* @Date: 2020/07/28 21:04:26
* @Version: V1.0
**/
@Controller
public class UsersController {
@RequestMapping("/addUser")
// public String showPage(){
public String showPage(@ModelAttribute("aa") Users users){
return "add";
}
/**
* 完成用户添加
*@Valid 开启对Users对象的数据校验
*BindingResult:封装了校验的结果
*/
@RequestMapping("/save")
// public String saveUser(@Valid Users users, BindingResult result){
public String saveUser(@ModelAttribute("aa") @Valid Users users, BindingResult result){
if(result.hasErrors()){
return "add";
}
System.out.println(users);
return "ok";
}
}
3.前端代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>添加用户</title>
</head>
<body>
<!-- 类名的对象
<form th:action="@{/save}" method="post">
用户姓名:<input type="text" name="name" /><font color="red" th:errors="${users.name}"></font><br/><br/>
用户密码:<input type="password" name="password" /><font color="red" th:errors="${users.password}"></font><br/>
用户年龄:<input type="text" name="age" /><font color="red" th:errors="${users.age}"></font><br/>
<input type="submit" value="OK"/>
</form>
-->
<!--- 使用别名aa --->
<form th:action="@{/save}" method="post">
用户姓名:<input type="text" name="name" /><font color="red" th:errors="${aa.name}"></font><br/><br/>
用户密码:<input type="password" name="password" /><font color="red" th:errors="${aa.password}"></font><br/>
用户年龄:<input type="text" name="age" /><font color="red" th:errors="${aa.age}"></font><br/>
<input type="submit" value="OK"/>
</form>
</body>
</html>
4.结构调用: