Spring Thymelaf表单验证被忽略



我有一个带有thymelaf表单的Spring MVC应用程序,我正在尝试验证它,尽管验证被忽略了(基本示例,我不在表单中插入任何数据,然后直接单击"提交"(。

控制器

@GetMapping("/test")
public String getTest(Model model) {
model.addAttribute("emailContatti", new EmailContatti());
return "test";
}
@PostMapping("/test/validation")
public String testInputValidation(@Valid @ModelAttribute("emailContatti") EmailContatti emailContatti, BindingResult bindingResult) {
if (bindingResult.hasErrors()) return "contatti";
else return "email-inviata";
}

POJO

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class EmailContatti {
@NotBlank(message = "campo obbligatorio")
private String nome;
@NotBlank(message = "campo obbligatorio")
private String cognome;
@NotBlank(message = "campo obbligatorio")
@Email(message = "formato email invalido")
private String email;
@NotBlank(message = "campo obbligatorio")
@Size(min = 10, max = 13, message = "numero di telefono invalido")
private String telefono;
@NotBlank(message = "campo obbligatorio")
private String messaggio;

}

胸腺形式

<form action="#" th:action="@{/test/validation}" th:object="${emailContatti}" method="post">
<table>
<tr>
<td>Nome:</td>
<td><input type="text" th:field="*{nome}" /></td>
<td th:if="${#fields.hasErrors('nome')}" th:errors="*{nome}">Name Error</td>
</tr>
<tr>
<td>Cognome:</td>
<td><input type="text" th:field="*{cognome}" /></td>
<td th:if="${#fields.hasErrors('cognome')}" th:errors="*{cognome}">Cognome Error</td>
</tr>
<tr>
<td>Email:</td>
<td><input type="email" th:field="*{email}" /></td>
<td th:if="${#fields.hasErrors('email')}" th:errors="*{email}">Email Error</td>
</tr>
<tr>
<td>Numero telefono:</td>
<td><input type="text" th:field="*{telefono}" /></td>
<td th:if="${#fields.hasErrors('telefono')}" th:errors="*{telefono}">telefono Error</td>
</tr>
<tr>
<td>Messaggio:</td>
<td><input type="text" th:field="*{messaggio}" /></td>
<td th:if="${#fields.hasErrors('messaggio')}" th:errors="*{messaggio}">messaggio Error</td>
</tr>
<tr>
<td><button type="submit">Submit</button></td>
</tr>
</table>

因此,正如您所看到的,我确保在控制器中添加了model属性,并确保在@Valid注释之后插入BindingResult。

结果

表单被显示,代码运行没有问题,尽管验证被完全忽略;成功;(invia电子邮件(页面显示。

有什么想法吗?

感谢您的时间和经验

================编辑==========

通过在bindingResult.hasErrors((处添加断点,我看到它返回false。我也尝试过使用不同的注释验证,比如@NotNull@NotEmpty,但仍然没有成功的

if-else块是错误的,请更改您的代码,如下所示:

@PostMapping("/test/validation")
public String testInputValidation(@Valid @ModelAttribute("emailContatti") EmailContatti emailContatti, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "contatti";
}
return "email-inviata";
}

相关内容

  • 没有找到相关文章

最新更新