java - 使用 thymeleaf 和 bootstrap 未在验证表单上应用样式

标签 java spring-boot bootstrap-4 thymeleaf

尝试在引导表单中添加带有错误验证样式的文本

这是表格的一部分:

<label th:text="#{name}"
        class="col-form-label col-form-label-sm"></label> 
<input
        type="text" class="form-control form-control-sm"
        th:field="*{name}" /> 
<span
        th:if="${#fields.hasErrors('name')}" th:errors="*{name}"
        th:class="invalid-feedback">Here there is an error</span>

我收到有关验证错误的消息,但没有样式。

如果我调试,我会看到具有以下样式的类:

<span class="invalid-feedback">Here there is an error</span>

我尝试过几种样式,例如帮助阻止,但没有办法。

我正在使用 bootstrap4.0.0-alpha.6

有什么想法吗?

谢谢

最佳答案

如果您仍然感兴趣。

Bootstrap's current validation docs为您提供三种方法:客户端自定义验证、浏览器默认验证和服务器端验证。

根据您的帖子,我假设您正在使用服务器端,这意味着您正在发送要在服务器代码中进行验证的数据,以便在重新呈现表单时显示错误字段。

在这种情况下,请记住,为了启动 Bootstrap 的样式,您的代码需要特定的 html 结构,例如:

<input th:field ="*{email}" type="email" class="form-control"
        th:classappend="${not #lists.isEmpty(#fields.errors('email'))} ? is-invalid"
        required>
<div class="invalid-feedback">
    <p th:each="error: ${#fields.errors('email')}" th:text="${error}">Invalid data</p>
</div>

(我相信 span 标签也适用于 <div class="invalid-feedback"> )

这是错误样式正常工作的最小必要结构。会发生什么:

  1. 最初,invalid-feedback已分配display: none
  2. 表单已提交,如果有错误,将重新渲染,并由开发人员提供一种机制,其中包括 is-invalidclass每个 <input class="form-control"/> 的属性有错误。在前面的代码中,th:classappend="${not #lists.isEmpty(#fields.errors('email'))} ? is-invalid"是造成这种情况的原因。 (我是 Spring 和 Thymeleaf 的新手,因此可能有更简洁的代码)
  3. 声明.form-control.is-invalid~.invalid-feedback _forms.scss 将启动并分配 display: block<div class="invalid-feedback"> ,从而显示每个字段的错误消息。

这应该足以在每个字段下显示错误并以红色突出显示它们。

关于java - 使用 thymeleaf 和 bootstrap 未在验证表单上应用样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49743079/

相关文章:

java - 我可以在动态加载的 .jar(使用 ClassLoaders)中设置断点吗?

java - 结果集空指针异常

java - 原型(prototype) Bean 销毁

jquery - 如果我们禁用单击按钮,工具提示不会隐藏

html - 隐藏 wep 应用的侧边导航栏

java - android中不明确的列名

java - 如何为字符串到文件句柄的映射创建清理器?

amazon-web-services - 如何在AWS托管的Docker容器内通过Spring Boot加载静态文件?

java - Spring Boot中如何映射RSocket的所有交互模型

html - 容器流体中的中心容器