我想检查提交表单时是否选中了复选框。
我需要验证服务器端的用户输入,因此我使用的是Spring MVC Form验证器。
我正在使用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;
}
我的代码似乎工作正常,我不知道这是否正确。
答案 0 :(得分:1)
我只删除了th:field = * {checked},一切正常,这就是我所做的:
<input name="checked" class="form-check-input" type="checkbox" th:checked="*{checked}" />
并在控制器中:
@PostMapping(value = "/contact")
public String contactUsHome(@Valid @ModelAttribute("mailForm") final MailForm mailForm, BindingResult bindingResult)
throws MessagingException {
if (bindingResult.hasErrors()) {
return HOME_VIEW;
} else {
emailService.sendSimpleMail(mailForm);
return REDIRECT_HOME_VIEW;
}
}
对于验证,我使用了Spring Validation:
public class MailValidator implements Validator {
//...
@Override
public void validate(Object obj, Errors errors) {
//...
MailForm mailForm = (MailForm) obj;
validateChecked(errors, mailForm);
//...
}
private void validateChecked(Errors errors, MailForm mailForm) {
if (mailForm.isChecked() == false) {
errors.rejectValue("checked", "mailForm.checked");
}
}
}