【发布时间】:2018-05-09 22:09:41
【问题描述】:
我想检查提交表单时是否选中了复选框。
我需要在服务器端验证用户输入,所以我使用 Spring MVC 表单验证器。
我正在使用 UserFormValidator 类检查表单,但我没有找到如何验证字段复选框。
html代码:
<form method="post" th:action="@{/addUser}" th:object="${userForm}">
<!-- other fields ... -->
<input type="checkbox" name="isTermsChecked" value="" th:checked="${isChecked}">
<span class="text-danger" th:text="${errorTermsChecked}"></span>
<button type="submit">Get Started</button>
</form>
这就是我在 Controller 类中所做的:
@PostMapping(value = "/addUser")
public ModelAndView addUser(@Valid @ModelAttribute("userForm") UserForm userForm, BindingResult bindingResult, String isTermsChecked) {
ModelAndView modelAndView = new ModelAndView();
boolean isChecked = false;
System.out.println("isTermsChecked: "+isTermsChecked);
//check is checkbox checked
if (isTermsChecked == null) {
modelAndView.addObject("isChecked", isChecked);
modelAndView.addObject("errorTermsChecked", "Please accept the Terms of Use.");
}else{
isChecked = true;
modelAndView.addObject("isChecked", isChecked);
modelAndView.addObject("errorTermsChecked", "");
}
if (bindingResult.hasErrors() || isTermsChecked == null) {
modelAndView.setViewName("view_addUser");
} else {
//add user ...
modelAndView.setViewName("view_addUser");
}
return modelAndView;
}
我的代码似乎可以正常工作,但我不知道它是否正确。
【问题讨论】:
-
您不能在客户端执行此操作。 JavaScript / jquey ?
-
嗨,@want2learn 我们可以使用 JavaScript 在客户端验证用户输入,但必须在服务器端验证它们。
-
如果是这样,你为什么不在你的 userForm 对象上再添加一个字段 isTermsChecked 来验证它。
-
@want2learn 嗨,我尝试在 UserForm 类和 html 中添加一个字段,我尝试了这个
<input type="checkbox" name="isTermsChecked" th:field="*{isTermsChecked}">,但它对我不起作用我在复选框输入中出现错误,但我做到了不记得这个错误,因为我正在尝试其他解决方案。我还没有找到一个例子。 -
@want2learn 我在 userForm 上添加了一个字段并且验证有效,但是当我使用
th:field="*{termsChecked}"时,我无法选中或取消选中视图中的复选框输入。
标签: spring spring-mvc thymeleaf spring-validator