2
respostas

Spring boot validação

Olá, pessoal! Estou tentando utilizar a validação do spring boot porém sem sucesso. Ao submeter o formulário no lugar dele executar a lógica do método a seguinte página de erro abaixo está sendo mostrada. Alguém sabe dizer pq?

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Sat Nov 24 15:33:26 BRT 2018
There was an unexpected error (type=Bad Request, status=400).
Validation failed for object='travelAgency'. Error count: 1
org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'travelAgency' on field 'cnpj': rejected value []; codes [NotBlank.travelAgency.cnpj,NotBlank.cnpj,NotBlank.java.lang.String,NotBlank]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [travelAgency.cnpj,cnpj]; arguments []; default message [cnpj]]; default message [must not be blank]

Código utilizado no projeto

Modelo

@Entity
@Table(name = "travel_agencies")
public class TravelAgency {

    public static final String SEQUENCE_NAME = "travel_agencies_id_seq";

    @Id
    @SequenceGenerator(name = SEQUENCE_NAME, sequenceName = SEQUENCE_NAME, allocationSize = 1)
    @GeneratedValue(generator = SEQUENCE_NAME, strategy = GenerationType.SEQUENCE)
    private Integer id;

    @NotBlank
    private String cnpj;

    @Column(name = "tranding_name")
    private String tradingName;

    @Column(name = "business_name")
    private String businessName;

    private String phone;

    private String email;

    private boolean enabled = true;
}

Controle

@Controller
@RequestMapping("/account")
public class AccountController {

    @Autowired
    private AccountService accountService;

    @GetMapping("/create")
    public String create(Model model, TravelAgency travelAgency, User user) {
        model.addAttribute("travelAgency", travelAgency);
        model.addAttribute("user", user);
        return "/account/create";
    }

    @GetMapping("/success")
    public String success() {
        return "/account/success";
    }

    @GetMapping("/error")
    public String error() {
        return "/account/error";
    }

    @PostMapping("/save")
    public String save(Model model, @Valid TravelAgency travelAgency, BindingResult errors)  {
        if (errors.hasErrors()) {
            return "/account/error";
        }
        accountService.save(travelAgency, user);
        return "redirect:/account/success";
    }
}

Formulário

    <form method="post" th:action="@{/account/save}"
      th:object="${travelAgency}">
      <div class="card ui-sigavi-card">
        <div class="card-header">
          <h1 class="title">Nova conta</h1>
        </div>
        <div class="card-body">
          <fieldset>
            <legend>Dados da agência</legend>

            <div class="form-row">
              <div class="form-group col-lg-4">
                <label for="inputEmail4" class="required">CNPJ</label> <input
                  type="tel" class="form-control cnpj-mask"
                  th:field="*{cnpj}">
              </div>
              <div class="form-group col-lg-8">
                <label for="inputPassword4" class="required">Nome
                  comercial</label> <input type="text" class="form-control"
                  th:field="*{tradingName}" maxlength="100">
              </div>
            </div>

            <div class="form-row">
              <div class="form-group col-lg-4">
                <label for="inputEmail4" class="required">Telefone</label>
                <input type="tel" class="form-control phone-mask"
                  th:field="*{phone}" maxlength="15"
                  placeholder="DDD + Número">
              </div>
              <div class="form-group col-lg-8">
                <label for="inputPassword4" class="required">E-mail</label>
                <input type="email" class="form-control"
                  th:field="*{email}" maxlength="100">
              </div>
            </div>
          </fieldset>
        </div>

        <div class="card-footer">
          <p>
            Ao clicar em <span class="text-uppercase">Criar conta</span>,
            você concorda com nossos <a href="">Termos</a>.
          </p>
          <button type="submit" class="btn btn-success">Criar
            conta</button>
        </div>
      </div>
      <!-- /card -->
    </form>
2 respostas

Oi Phillip, você está enviando o formulário com o cnpj vazio??

Olá, Guilherme!

Sim! O correto seria ele executar esse trecho de código com o CNPJ vázio:

        if (errors.hasErrors()) {
            return "/account/error";
        }

Pórem, o método não está sendo chamado.