Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In Spring 3 the <em>best</em> way to go <em>is</em> to use annotations, if you can switch. The integration with the bean validation API makes it easy to add validation. All you have to do to validate a form bean is to add the @Valid (see "5.7.4.1 Triggering @Controller Input Validation" in the Spring MVC docs chapter "5. Validation, Data Binding, and Type Conversion") annotation to a controller method argument. Spring will then validate the bean and put the validation errors into a BindingResult for you.</p> <pre><code>@Controller public class RegisterFormController { ... @RequestMapping(value = "/register", method = RequestMethod.POST) public String submitFormHandler(@ModelAttribute("registration") @Valid User user, BindingResult errors) { if (errors.hasErrors()) { // send user back to form view } else { // handle form submission } } ... } </code></pre> <p>The docs say that Spring will automatically set up the bean validation factories and validators, but if that doesn't work for you, you can manually configure it very easily:</p> <pre><code> &lt;bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"&gt; &lt;property name="webBindingInitializer"&gt; &lt;!-- Configures Spring MVC DataBinder instances --&gt; &lt;bean class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer"&gt; &lt;property name="validator" ref="validator" /&gt; &lt;/bean&gt; &lt;/property&gt; &lt;/bean&gt; &lt;!-- Creates the JSR-303 Validator --&gt; &lt;bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" /&gt; </code></pre> <p>I also created a project based on the client-side implementation of "valang" validation from the validation Spring Module that can provide client-side validation in JavaScript based on the JSR-303 and Hibernate Validator validation annotations.</p> <p><a href="http://kenai.com/projects/jsr303js" rel="nofollow noreferrer">http://kenai.com/projects/jsr303js</a></p> <p>The project provides a taglib/JavaScript file that you include to put the main JavaScript code into the page, then another tag that you put somewhere in your Spring <code>&lt;form:form&gt;&lt;/form:form&gt;</code> tag to trigger the validation.</p> <pre><code>&lt;%@ taglib prefix="jsr303js" uri="http://kenai.com/projects/jsr303js/" %&gt; ... &lt;head&gt; ... &lt;script type="text/javascript" src="&lt;c:url value="/js/jsr303js-codebase.js"/&gt;"&gt;&lt;/script&gt; ... &lt;/head&gt; &lt;body&gt; ... &lt;form:form name="regForm" commandName="registration" method="post"&gt; ... &lt;jsr303js:validate commandName="registration"/&gt; ... &lt;/form:form&gt; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload