尝试在引导表单中添加带有错误验证样式的文本
这是表格的一部分:
<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">
)
这是错误样式正常工作的最小必要结构。会发生什么:
- 最初,
invalid-feedback
已分配display: none
- 表单已提交,如果有错误,将重新渲染,并由开发人员提供一种机制,其中包括
is-invalid
在class
每个<input class="form-control"/>
的属性有错误。在前面的代码中,th:classappend="${not #lists.isEmpty(#fields.errors('email'))} ? is-invalid"
是造成这种情况的原因。 (我是 Spring 和 Thymeleaf 的新手,因此可能有更简洁的代码) - 声明
.form-control.is-invalid~.invalid-feedback
_forms.scss 将启动并分配display: block
至<div class="invalid-feedback">
,从而显示每个字段的错误消息。
这应该足以在每个字段下显示错误并以红色突出显示它们。
嗨
关于java - 使用 thymeleaf 和 bootstrap 未在验证表单上应用样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49743079/