0

I need to capture validation errors for send to View. I followed several tutorials that way: My Method with Bean validation:

   @RequestMapping(value = "/novo", method = RequestMethod.POST)
    public ModelAndView salvar(@Valid Cliente cliente, BindingResult result
        , RedirectAttributes attributes) {
    if (result.hasErrors()) {
        return novo(cliente);
    }

    ModelAndView mv = new ModelAndView("redirect:/clientes/novo");
    attributes.addFlashAttribute("mensagem", "Cliente salvo com sucesso.");
    return mv;
}

My class Cliente:

 public class Cliente implements EntityModal<Long> {

private Long id;

@NotBlank(message = "Nome é obrigatório")
private String nome;

@CPF(message = "CPF inválido")
private String cpf;

@NotNull(message = "Informe o sexo")
private Sexo sexo;

@NotNull(message = "Idade é obrigatória")
@Min(value = 18, message = "Idade deve ser maior ou igual que 18")
private Integer idade;

@Size(max = 50, message = "A observação não pode ter mais que 50 caracteres")
private String observacao;
 //get and setters...
}

error:

An Errors/BindingResult argument is expected to be declared immediately 
after the model attribute, the @RequestBody or the @RequestPart arguments to 
which they  apply: public org.springframework.web.servlet.ModelAndView
joeyanthon
  • 208
  • 1
  • 2
  • 13

1 Answers1

0

Add @ModelAttribute in your model object.

@RequestMapping(value = "/novo", method = RequestMethod.POST)
public ModelAndView salvar(@Valid @ModelAttribute("cliente") Cliente cliente, BindingResult result
        , RedirectAttributes attributes) {

}
Monzurul Shimul
  • 8,132
  • 2
  • 28
  • 42