在Spring MVC中,请定义一个表单,用于注册员工的信息,属性包括:姓名、生日、入职日期、电话、备用电话等,其实,属性的验证规则如下: 姓名:必填,长度在6~10个之间 生日:必须是正确的日期格式,而且早于当前时间 入职日期:必填 电话:只能是手机号码 备用电话:只能是座机号码 请使用Validation框架完成此功能。
时间: 2024-03-11 17:47:41 浏览: 17
好的,下面是一个简单的示例代码:
首先定义一个实体类Employee,包含要验证的属性:
```java
public class Employee {
@NotBlank(message = "姓名不能为空")
@Length(min = 6, max = 10, message = "姓名长度必须在6~10之间")
private String name;
@NotNull(message = "生日不能为空")
@Past(message = "生日必须早于当前时间")
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date birthday;
@NotNull(message = "入职日期不能为空")
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date hireDate;
@Pattern(regexp = "^1[3456789]\\d{9}$", message = "电话号码格式不正确")
private String phone;
@Pattern(regexp = "^0\\d{2,3}-\\d{7,8}$", message = "座机号码格式不正确")
private String backupPhone;
// getters and setters
}
```
然后,在控制器中定义一个处理注册请求的方法,使用@Valid注解和BindingResult对象进行验证:
```java
@Controller
public class EmployeeController {
@PostMapping("/register")
public String register(@Valid @ModelAttribute Employee employee, BindingResult result) {
if (result.hasErrors()) {
// 如果验证出错,返回注册页面,并提示错误信息
return "register";
}
// 如果验证通过,保存员工信息,并跳转到成功页面
// ...
return "success";
}
}
```
最后,在注册页面中,使用thymeleaf模板引擎生成表单,并使用th:errors指令显示验证错误信息:
```html
<form action="/register" method="post" th:object="${employee}">
<div>
<label for="name">姓名:</label>
<input type="text" id="name" name="name" th:field="*{name}">
<span th:if="${#fields.hasErrors('name')}" th:errors="*{name}"></span>
</div>
<div>
<label for="birthday">生日:</label>
<input type="date" id="birthday" name="birthday" th:field="*{birthday}">
<span th:if="${#fields.hasErrors('birthday')}" th:errors="*{birthday}"></span>
</div>
<div>
<label for="hireDate">入职日期:</label>
<input type="date" id="hireDate" name="hireDate" th:field="*{hireDate}">
<span th:if="${#fields.hasErrors('hireDate')}" th:errors="*{hireDate}"></span>
</div>
<div>
<label for="phone">电话:</label>
<input type="text" id="phone" name="phone" th:field="*{phone}">
<span th:if="${#fields.hasErrors('phone')}" th:errors="*{phone}"></span>
</div>
<div>
<label for="backupPhone">备用电话:</label>
<input type="text" id="backupPhone" name="backupPhone" th:field="*{backupPhone}">
<span th:if="${#fields.hasErrors('backupPhone')}" th:errors="*{backupPhone}"></span>
</div>
<div>
<button type="submit">提交</button>
</div>
</form>
```
以上是一个简单的示例代码,可以根据实际需求进行修改和扩展。