Spring MVC validation error in nested Entity

Asked

Viewed 145 times

2

You guys all right? I started studying Spring recently by the courses of Algaworks and at the course progress I came across a problem in a project the part that I am developing.

I have an Entity School that has the following characteristics:

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

@NotNull(message = "Código INEP é obrigatório")
@Column(name = "codigo_inep", unique = true)
private Integer codigoINEP;

@NotEmpty(message = "Nome é obrigatória")
@Size(max = 100, message = "O nome não pode conter mais de 100 caracteres")
@Column(length = 100, nullable = false)
private String nome;

@Column(name = "telefone", length = 16)
private String telefone;

@Column(name = "celular", length = 16)
private String celular;

@Email(message = "E-mail inválido")
@Column(length = 80)
private String email; 

And my Address is as follows:

@NotEmpty(message = "Logradouro é obrigatório")
@Column(length = 80)
private String logradouro;

@Column(length = 10)
private String numero;

@Column(length = 80)
private String complemento;

@NotEmpty(message = "Bairro é obrigatório")
@Column(length = 60)
private String bairro;

@NotEmpty(message = "Município é obrigatório")
@Column(length = 60, nullable = false)
private String municipio;

@NotEmpty(message = "CEP é obrigatório")
@Column(length = 10)
private String cep;

@Enumerated(EnumType.STRING)
@Column(length = 2, nullable = false)
private Uf uf;

@Enumerated(EnumType.STRING)
@Column(length = 8)
private Localizacao localizacao;

@Column(length = 60)
private String distrito;

In my control the mapped method to access the School Register view is as follows:

@RequestMapping("/nova")
public ModelAndView nova() {

    ModelAndView mv = new ModelAndView(CADASTRO_VIEW);
    Escola escola = new Escola();
    escola.setEndereco(new Endereco());
    mv.addObject(escola);

    return mv;
}

And the method mapped to save is that way:

@RequestMapping(method = RequestMethod.POST)
public String salvar(@Validated Escola escola, Errors erros, RedirectAttributes attributes) {

    if (erros.hasErrors()) {
        return CADASTRO_VIEW;
    }

    escolas.save(escola);

    attributes.addFlashAttribute("mensagem", "Escola salva com sucesso!");

    return "redirect:/escola/nova";
}

I used this code snippet to list errors in my School Register View:

<div class="alert alert-danger" th:if="${#fields.hasAnyErrors()}">

    <div th:each="detailedError : ${#fields.detailedErrors()}">
        <span th:text="${detailedError.message}"></span>
    </div>

</div>

And this attribute in each input to turn the input red if you have any validation error:

<div class="form-group" th:classappend="${#fields.hasErrors('nome')} ? 'has-error'" >

                    <label for="nome" class="col-sm-2 control-label" >Nome</label>

                    <div class="col-sm-4" >
                        <input type="text" class="form-control" id="nome" th:field="*{nome}" placeholder="Informe o seu nome" />
                    </div>

                </div>

In the input name if you do not enter any value the error appears and the field turns red, but in the input cep below does not appear, below follows the same:

<div class="form-group" th:classappend="${#fields.hasErrors('endereco.cep')} ? 'has-error'" >

                    <label for="cep" class="col-sm-2 control-label"  >CEP</label>

                    <div class="col-sm-2" >
                        <input type="text" class="form-control js-cep" id="cep" th:field="*{endereco.cep}" placeholder="00000-000" />
                    </div>

                </div>

How do I catch these validation errors of Entity School and display on my page, thanks in advance. Vlw guys.

1 answer

1


In Entity Escola that you placed there is an attribute Endereco. You forgot to put it?

If there is an address attribute in the class Escola, add the annotation @Valid:

@NotNull
@Valid
private Endereco endereco;
  • Good morning Felipe Marinho had put yes, just forgot to show him in the body of the School Entity above. Now it’s working properly, thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.