validate input in Thymeleaf

后端 未结 2 1772
[愿得一人]
[愿得一人] 2021-01-07 09:20

I have this input:

Masa: 
    
2条回答
  •  时光说笑
    2021-01-07 09:49

    It seems like you want to implement server side validation. For this the best approach is to use validators and its bindingResult. Steps to implement server side validation is

    1. Have for model

      public class PersonForm {
        private String name;
      
       public String getName() {
          return this.name;
      }
      
       public void setName(String name) {
          this.name = name;
      }
      }
      
    2. Use form model in html

      Generic Error
      1. Have validator class

      @Component

      public class PersonFormValidator implements Validator {
      @Override
      public boolean supports(Class clazz) {
          return PersonForm.class.equals(clazz);
      }
      
      @Override
      public void validate(Object target, Errors errors) {
          ValidationUtils.rejectIfEmpty(errors, "name", "field.name.empty");
          PersonForm p = (PersonForm) target;
      
          if (p.getName().equalsIgnoreCase("XXX")) {
              errors.rejectValue("name", "Name cannot be XXX");
          }
      }}
      
      1. Bind validator to controller and let spring do the magic.

      @Controller

      public class WebController {
      @Autowired
      PersonFormValidator personFormValidator;
      
      
      @InitBinder("personForm")
      protected void initPersonFormBinder(WebDataBinder binder) {
      binder.addValidators(personFormValidator);
      }
      
      @PostMapping("/personForm")
      public String checkPersonInfo(@Validated PersonForm personForm, BindingResult bindingResult, final RedirectAttributes redirectAttributes) {
      if (bindingResult.hasErrors()) {
          return "personForm";
      }
      redirectAttributes.addFlashAttribute("personResult",  apiClientService.getPersonResult(personForm));
      return "redirect:/spouseForm";
      }
      }
      

提交回复
热议问题