Thymeleaf not displaying Spring form error messages

前端 未结 3 1870
北荒
北荒 2020-12-14 06:55

I\'m migrating a Spring jsp application to Thymeleaf but having problems displaying form errors.

I\'m using the SpringTemplateEngine and ThymeleafViewResolver and re

相关标签:
3条回答
  • 2020-12-14 07:10

    This is how I do it in my forms:

    For displaying all errors I put this at the beginning of my form:

    <div class="alert alert-danger" th:if="${#fields.hasErrors('*')}">
        <p th:each="err : ${#fields.errors('*')}" th:text="${err}"></p>    
    </div>
    

    and for individual error I add this after the field (of course, changing field in hasErrors to correspond to the field tested):

    <p th:if="${#fields.hasErrors('vehicle.licensePlate')}" class="label label-danger" th:errors="*{vehicle.licensePlate}">Incorrect LP</p>
    

    Let me know if this works for you?

    0 讨论(0)
  • 2020-12-14 07:20

    I think you may be having the same issue as I did - please see :

    • Fields object functions (Spring)

    There it is answered by Daniel Fernandez. Basically your form object th:object="${form}" is named "form" but your controller is looking for "customerForm" (class name) not "form" (the variable name)

    can be renamed with @ModelAttribute("data")

    copied from that link use:

    public String post(@Valid FormData formData, BindingResult result, Model model){
        // th:object="${formData}"
    }
    

    or

    public String post(@Valid @ModelAttribute("data") FormData data, BindingResult result, Model model){
        // th:object="${data}"
    } 
    
    0 讨论(0)
  • 2020-12-14 07:29

    Adding to @Blejzer answer: naming of error message inside messages.properties file must follow below naming convention, so message string will be returned instead of message key:

    (Constraint Name).(Object Name).(Property Name)

    note: Object Name not Class Name

    For example, if you have below User class:

    class User{
        @NotBlank
        String username;
    
        @Length(min=6)
        String password;
    }
    

    suppose in controller, we named object under validation "user", see @ModelAttribute("user"):

    @RequestMapping(value = "/signup", method = RequestMethod.POST)
    public String signup(@Valid @ModelAttribute("user") User user, BindingResult bindingResult, Model model) {
    
        if (bindingResult.hasErrors()) {
            return "signup";
        }
    
        //do some processing
    
        return "redirect:/index";
    }
    

    in above controller snippet, the object name is "user" not "User"

    Now, to show custom messages, you have to name the message as below:

    NotBlank.user.username=User Name is blank
    Length.user.password=Password length must be at least 6 letters
    
    0 讨论(0)
提交回复
热议问题