注册数据校验
注册参数
@Data
public class UserRegisterVo {
@NotEmpty(message = "用户名必须填写")
@Length(min = 6, max = 18, message = "用户名必须6~18为字符")
private String userName;
@NotEmpty(message = "密码必须填写")
@Length(min = 6, max = 18, message = "密码必须6~18为字符")
private String password;
@NotEmpty(message = "手机号必须填写")
@Pattern(regexp = "^[1]([3-9])[0-9]{9}$", message = "手机号格式不正确")
private String phone;
@NotEmpty(message = "验证码必须填写")
private String code;
}
@Validated 表示需要校验
BindingResult result 获取校验结果
@PostMapping("/regist")
public String register(@Validated @RequestBody UserRegisterVo vo,
BindingResult result,
RedirectAttributes redirectAttributes) {
if (result.hasErrors()) {
Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(fieldError -> {
return fieldError.getField();
}, fieldError -> {
return fieldError.getDefaultMessage();
}));
// model.addAttribute("errors", errors);
redirectAttributes.addFlashAttribute("errors", errors);
//转发地址栏没有变化;重定向地址栏有变化
//校验出错,重定向到注册页
return "redirect:http://auth.mall.com/reg.html";
}
}