Search code examples
formsvalidationspring-bootthymeleaf

Springboot Thymeleaf form validation not working


I've trying to validate the fields in Thymeleaf but the errors are not showing in the view page.

My Controller

@Controller
public class UserController {

    private static final String ADD_NEW_USER="user/addUser";

    @Autowired
    UserService userService;
        @RequestMapping(value="/user/new", method=RequestMethod.GET)
    public String addUser(Registration register, Model model){
        model.addAttribute("register",register);
        return ADD_NEW_USER;
    }

    @RequestMapping(value="/user/new", method=RequestMethod.POST)
    public String addUser(@Valid Registration register, BindingResult result, Model model){
        model.addAttribute("register",register);
        if(result.hasErrors()){
           List<FieldError> err=result.getFieldErrors();

           for(FieldError e:err){
                System.out.println("Error on object ---> "+e.getObjectName()+" on field ---> "+e.getField()+". Message ---> "+e.getDefaultMessage());
           }
           return ADD_NEW_USER;
        }
        return INDEX_PAGE;
    }
}

View template

<form th:action="@{/user/new}" th:method="post" th:object="${register}" id="addUser" role="form">
    <fieldset>
        <legend> 
            <p>Field with <span class="required">*</span> are required</p>
        </legend>
        <div class="form-group">     
            <label for="name"><span class="required">* </span>Name: </label>
            <input type="text" th:field="*{name}" class="form-control" /> 
            <div th:if="${#fields.hasErrors('name')}" th:errors="*{name}" class="alert alert-danger">
            <p>Name is invalid</p>
            </div>
            <p class="help-block">Please provide full name for the user</p>
        </div>
        <div class="form-group">
            <label for="email"><span class="required">* </span> Email Address: </label> 
            <input class="form-control" type="email" th:field="*{email}"/>
            <div th:if="${#fields.hasErrors('email')}" th:errors="*{email}" class="alert alert-danger">
                <p>Email is invalid</p>
            </div>
            <p class="help-block">Please provide a valid email address. Activation link will be sent to this email</p>
        </div>
        <div class="form-group">
            <label for="password"><span class="required">* </span> Password: </label>
            <input type="password" th:field="*{password}" class="form-control"/>
        </div>
        <div class="form-group">
            <input class="btn btn-success" type="submit" name="Register" value="Register"/>
        </div>

    </fieldset>
</form><!-- ends register form -->

Modal

@Entity
public class Registration {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;

    @NotEmpty
    @Size(min=3, max=50)
    @Column(nullable=false)
    private String name;

    @Email
    @NotEmpty
    @Column(nullable=false)
    private String email;

    private String password;

   //getters and setters
}

I can output the console error like this.

Error on object ---> registration on field ---> name. Message ---> size must be between 3 and 50
Error on object ---> registration on field ---> email. Message ---> may not be empty
Error on object ---> registration on field ---> name. Message ---> may not be empty

I might be missing something but unable to find.


Solution

  • the problem is that the name of the entity is Registration and that the name of the object that you use is register.

    In order this to work add @ModelAttribute("register") next yo your @valid annotation namely

     @RequestMapping(value="/user/new", method=RequestMethod.POST)
        public String addUser(@Valid @ModelAttribute("register") Registration register, BindingResult result, Model model){
    

    Hope this helps