Spring form validation using annotation and @Valid

I am having some issues with my form validation.

Controller:

@RequestMapping(value = REGISTER_URL, method = RequestMethod.POST) public String registerPost(@Valid RegisterForm registerForm, BindingResult result) { if (result.hasErrors()) { return REGISTER_VIEW; } System.out.println(registerForm.getPassword()); return LOGIN_VIEW; }

View:

<form:form action="register" commandName="registerForm" method="post"> <table> <tr> <td>Username:</td> <td><form:input path='username' /></td> <td><form:errors path="username"/></td> </tr> <tr> <td>Password:</td> <td><form:password path='password'/></td> <td><form:errors path="password"/></td> </tr> <tr> <td>Repeat password:</td> <td><form:password path='repeatedPassword'/></td> <td><form:errors path="repeatedPassword"/></td> </tr> <tr> <td colspan="2">&nbsp;</td> </tr> <tr> <td colspan='2'><input name="submit" type="submit">&nbsp;<input name="reset" type="reset"></td> </tr> </table> </form:form>

Form:

public class RegisterForm { @Size(min = 3, max = 15) private String username; @Size(min = 5) private String password; @Size(min = 5) private String repeatedPassword; // getters and setters omitted }

When i enter empty values (username, password and repeatedPassword) then no errors occurs (i have checked it using debugger). So it looks like no validation is performed. Binding values from view is ok (checked using debugger) Any ideas what might be wrong?

--------------Solutions-------------

Add following content into your context:

<mvc:annotation-driven />
<context:component-scan base-package="xxx.xxx.xxx" />

In the guide, they use "@SpringBootApplication" http://spring.io/guides/gs/validating-form-input/

The @SpringBootApplication annotation is equivalent to using @Configuration, @EnableAutoConfiguration and @ComponentScan with their default attributes: http://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-using-springbootapplication-annotation.html

Where is

<form action="register">

coming from? As it sounds as though no event is actually being triggered upon form submission.

Try changing it to:

action="${pageContext.request.contextPath}/login"

(or whatever page you want to forward a user to upon authentication)

Category:java Time:2018-11-26 Views:2

Related post

Copyright (C) pcaskme.com, All Rights Reserved.

processed in 0.578 (s). 14 q(s)