Springboot Thymeleaf表单验证无效

时间:2017-03-18 16:21:19

标签: forms validation spring-boot thymeleaf

我试图验证Thymeleaf中的字段,但错误未显示在视图页面中。

我的控制器

@Controller
public class UserController {

    private static final String ADD_NEW_USER="user/addUser";

    @Autowired
    UserService userService;
        @RequestMapping(value="/user/new", method=RequestMethod.GET)
    public String addUser(Registration register, Model model){
        model.addAttribute("register",register);
        return ADD_NEW_USER;
    }

    @RequestMapping(value="/user/new", method=RequestMethod.POST)
    public String addUser(@Valid Registration register, BindingResult result, Model model){
        model.addAttribute("register",register);
        if(result.hasErrors()){
           List<FieldError> err=result.getFieldErrors();

           for(FieldError e:err){
                System.out.println("Error on object ---> "+e.getObjectName()+" on field ---> "+e.getField()+". Message ---> "+e.getDefaultMessage());
           }
           return ADD_NEW_USER;
        }
        return INDEX_PAGE;
    }
}

查看模板

<form th:action="@{/user/new}" th:method="post" th:object="${register}" id="addUser" role="form">
    <fieldset>
        <legend> 
            <p>Field with <span class="required">*</span> are required</p>
        </legend>
        <div class="form-group">     
            <label for="name"><span class="required">* </span>Name: </label>
            <input type="text" th:field="*{name}" class="form-control" /> 
            <div th:if="${#fields.hasErrors('name')}" th:errors="*{name}" class="alert alert-danger">
            <p>Name is invalid</p>
            </div>
            <p class="help-block">Please provide full name for the user</p>
        </div>
        <div class="form-group">
            <label for="email"><span class="required">* </span> Email Address: </label> 
            <input class="form-control" type="email" th:field="*{email}"/>
            <div th:if="${#fields.hasErrors('email')}" th:errors="*{email}" class="alert alert-danger">
                <p>Email is invalid</p>
            </div>
            <p class="help-block">Please provide a valid email address. Activation link will be sent to this email</p>
        </div>
        <div class="form-group">
            <label for="password"><span class="required">* </span> Password: </label>
            <input type="password" th:field="*{password}" class="form-control"/>
        </div>
        <div class="form-group">
            <input class="btn btn-success" type="submit" name="Register" value="Register"/>
        </div>

    </fieldset>
</form><!-- ends register form -->

模态

@Entity
public class Registration {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;

    @NotEmpty
    @Size(min=3, max=50)
    @Column(nullable=false)
    private String name;

    @Email
    @NotEmpty
    @Column(nullable=false)
    private String email;

    private String password;

   //getters and setters
}

我可以像这样输出控制台错误。

Error on object ---> registration on field ---> name. Message ---> size must be between 3 and 50
Error on object ---> registration on field ---> email. Message ---> may not be empty
Error on object ---> registration on field ---> name. Message ---> may not be empty

我可能会遗漏一些但无法找到的东西。

3 个答案:

答案 0 :(得分:3)

我也面临着同样的问题。使用may hit / trial方法,我发现@Valid注释不适用于spring 2.3.0.RELEASE

如果您使用的是spring 2.3.0.RELEASE,请在下面添加依赖项

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>

希望这会有所帮助。

答案 1 :(得分:2)

问题是该实体的名称是注册,并且您使用的对象的名称是注册的。

为了实现这一点,请在@valid注释旁边添加@ModelAttribute(“register”) 即

 @RequestMapping(value="/user/new", method=RequestMethod.POST)
    public String addUser(@Valid @ModelAttribute("register") Registration register, BindingResult result, Model model){

希望这有帮助

答案 2 :(得分:1)

我也面临同样的问题。尽管在表单中没有提取任何值,但我的bindingResult.hasErrors()总是返回true。我不得不将验证从@NotNull更改为@NotEmpty。

@NotNull只会验证对象是否为空,@ NoEmpty将检查对象是否有空字符串。