viniciusalvess
viniciusalvess

Reputation: 814

@Valid form validation not working with Thymeleaf Spring Boot

The @Valid annotation does not trigger the validation when the post request arrives at the controller method. What should I do ?

Parent Controller:

    public class ApplicationController {

    @Autowired
    private I18NService i18NService;

    public I18NService getI18NService() {
        return i18NService;
    }

    public void setI18NService(I18NService i18NService) {
        this.i18NService = i18NService;
    }
}

The Layout Controller:

public class ClientLayoutController extends ApplicationController{

    @Autowired
    private UserService userService;

    @Autowired
    private ClienteService clienteService;

    protected ModelAndView getModelAndView(String aActiveMenu, String aI18n, String aViewName){
        ModelAndView mav = new ModelAndView();
        User user = userService.getAuthenticatedUser();
        Cliente cliente = clienteService.getAuthenticatedCliente();

        mav.addObject("active_menu",aActiveMenu);
        mav.addObject("titulo",this.getI18NService().getMessage(aI18n));
        mav.addObject("user",user);
        mav.addObject("cliente",cliente);
        mav.setViewName(aViewName);
        return mav;
    }
// Getters ans Setters...
}

The Controller that the request comes in:

@Controller
public class ClienteController extends ClientLayoutController {

    @GetMapping("/client/profile")
    public ModelAndView clientProfile() {
        ModelAndView mav = this.getModelAndView("profile","client.profile","store/account-profile");
        return mav;
    }

    @PostMapping("/client/profile")
    public ModelAndView clientProfileUpdate(@Valid Cliente cliente,BindingResult bindingResult,Model model) {
        System.out.println("sdfsdf "+cliente.getNome());
        System.out.println(bindingResult.getErrorCount());

        if(bindingResult.hasErrors()){
            ModelAndView mav = this.getModelAndView("profile","client.profile","store/account-profile");
            mav.addObject("cliente",cliente);
            return mav;
        }

        return this.getModelAndView("profile","client.profile","store/account-profile");
    }

}

Thymeleaf Form:

<form th:method="post" th:action="@{'/client/profile'}" th:object="${cliente}">
    <div class="form-group">
        <label for="nomecli" th:text="#{client.profile.name}">First Name</label>
        <input th:field="*{nome}" type="text" id="nomecli" class="form-control" th:placeholder="#{client.profile.name}"/>
        <span th:if="${#fields.hasErrors('nome')}" th:errors="*{nome}" class="text-danger"></span>
    </div>            
    <button type="submit" class="btn btn-default btn-theme" th:inline="text"><i class="fa fa-check"></i> [[#{crud.save}]]</button>
</form>

The Entity :

@Entity(name = "cliente")
public class Cliente {

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

    @Column(name = "nome")
    @NotEmpty(message = "Informe o nome")
    private String nome;

// Other fields...
}

the bindingResult.getErrorCount() is always 0 even though I post a blank form. I have tried adding the @NotNull and a lot of other things on google, but no success.

Upvotes: 2

Views: 3017

Answers (2)

viniciusalvess
viniciusalvess

Reputation: 814

Removed all custom validators I had on the application and removed all @InitBinders that I had on my others controllers to custom validate them. Now the @Valid has the expected behavior. After I found that out by myself, the post below explains better.

Spring - mixing annotation and validator-based validations

Upvotes: 2

balag3
balag3

Reputation: 665

Add @ModelAttribute("cliente") to your controller's signature as follows:

public ModelAndView clientProfileUpdate(@Valid @ModelAttribute("cliente") Cliente cliente, BindingResult bindingResult,Model model) {...}

On the other hand, you are passing an Entity to the view, which is used to represent a database entry. Use a data transfer object, which is just a simple POJO class and add the @NotNull or @NotEmpty annotations to it's fields.

Upvotes: 1

Related Questions