Reputation: 1709
I want to check if the checkbox is checked when submitting a form.
I need to validate the user input at server side so I am using Spring MVC Form validator.
I am checking the form with a UserFormValidator class but I do not find how to validate the field checkbox.
The html code:
<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>
That's what I did in the Controller class:
@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;
}
My code seems to work correctly and I do not know if it's the correct way.
Upvotes: 0
Views: 4960
Reputation: 1709
I only removed th:field=*{checked} and everything is working properly and that's what I did:
<input name="checked" class="form-check-input" type="checkbox" th:checked="*{checked}" />
and in the controller:
@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;
}
}
and for the validation I used 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");
}
}
}
Upvotes: 2