Home > Blockchain >  Using thymeleaf to display an error message alters the layout of my login form
Using thymeleaf to display an error message alters the layout of my login form

Time:11-24

I am using Thymeleaf to display an error message on my Login form upon entering wrong credentials:

<body>
  <div class="container">
    <form class="form" id="login" th:action="@{/login}" method="post">
      <h1 class="form__title">Login</h1>
      <div th:if="${param.error}" class="form__message form__message-error">
        invalid username or password
      </div>
  </div>
</body>

Since this error-message div only appears upon entering wrong credentials, my form changes its layout - the input fields are moving downwards. I don't want this. I want the form to look the same in either way, only the message is supposed to get written or deleted. Does anyone know how to achieve this?

CodePudding user response:

th:if will only add the <div> when the error request parameter is there. To do what you want, you should use CSS to either have an empty div or show some text, using th:classappend to select the CSS class to use.

Something like:

<body>
  <div class="container">
    <form class="form" id="login" th:action="@{/login}" method="post">
      <h1 class="form__title">Login</h1>
      <div th:classappend="${param.error}?'show':'hide'" class="form__message form__message-error">
        invalid username or password
      </div>
  </div>
</body>

With .show and .hide classes defined in your CSS.

  • Related