我正在使用Spring Thymeleaf,我在外部messages.properties文件中有表单验证消息。
当我像这样引用消息时:
th:attr="data-error=#{field.error.required.field}"
如下面的输入字段声明:
<input class="form-control input-lg" type="text" th:field="*{firstName}"
th:attr="data-error=#{field.error.required.field}" required="true"
data-delay="100" placeholder="First name"/>
当验证消息出现在浏览器中时,它的引号如下:
"This is a required field"
如何在没有引号的情况下显示消息?
这是一些更详细的代码。模型对象如下所示:
public class UserSession {
@Email
@NotEmpty
@Size(min = 2, max = 255)
private String email;
...
}
表单输入如下:
<div class="form-group" th:classappend="${#fields.hasErrors('email')} ? has-error">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span>
<input class="form-control input-lg" type="email" id="email"
th:field="*{email}" th:attr="data-error=#{field.error.invalid.email}"
required="true" data-delay="100" placeholder="Email"/>
</div>
<div class="help-block with-errors" th:errors="*{email}"></div>
<div class="help-block with-errors"></div>
</div>
当我删除data-error
属性并将消息直接绑定到模型对象属性时,我得到的是默认错误,而不是我的消息。
答案 0 :(得分:2)
您需要将@NotBlank / @NotNull绑定到表单类
你可以直接绑定message =“error.message”//你的属性变量
public class UserForm implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@NotBlank(message = "error.message")
private String firstName;
@NotBlank(message = "error.message")
private String lastName;
// your other filed with Getters and Setters
...........................
}
您的HTML代码:
<form role="form" th:action="@{/signup}" method="post" th:object="${userForm}">
<div class="row">
<div class="col-lg-12">
<th:block th:if="${#fields.hasErrors('${userForm.*}')}">
<div th:utext="Common error message">Alert</div>
</th:block>
<div class="form-group input-group" th:classappend="${#fields.hasErrors('firstName')}? 'has-error'">
<input type="text" th:field="*{firstName}" class="form-control" placeholder="firstName" />
<span class="help-block" th:if="${#fields.hasErrors('firstName')}" th:errors="*{firstName}">Incorrect title</span>
</div>
// your other filed with submit button
</div>
</div>
</form>
注意: