I am facing problem when i am doing server side form validation using jQuery and spring 4. Every time "result" (object of BindingResult) is coming with zero error result.
Below I am proving my code for better understanding. my jsp code is
<div class="registerForm">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Please Register</h4>
</div>
<div class="modal-body">
<form class="form-signin" id="regForm" commandName="userRegister">
<div class="reg-error error"></div><div class="reg-success success"></div>
<input type="text" name="username" class="input-block-level" placeholder="Username">
<input type="text" name="emailAddress" class="input-block-level" placeholder="Email address">
<input type="text" name="confirmEmailAdd" class="input-block-level" placeholder="Confirm Email address">
<input type="password" name="password" class="input-block-level" placeholder="Password">
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary submitRegister">Register</button>
</div>
</div>
my script code is
$.ajax({
url: "${pageContext.request.contextPath}/register",
data: $('#regForm').serialize(),
type: "POST",
success: function(result) {},
error: function(XMLHttpRequest, textStatus, errorThrown){}
});
My controller code is
@RequestMapping(value="/register", method = RequestMethod.POST)
public @ResponseBody
ValidationResponse register(Model model, @ModelAttribute("userRegister") @Valid UserRegister userReg, BindingResult result) {
ValidationResponse res = new ValidationResponse();
if(result.hasErrors()){
res.setStatus("FAIL");
List<FieldError> allErrors = result.getFieldErrors();
List<ErrorMessage> errorMesages = new ArrayList<ErrorMessage>();
for (FieldError objectError : allErrors) {
errorMesages.add(new ErrorMessage(objectError.getField(), objectError.getField() + " " + objectError.getDefaultMessage()));
}
res.setErrorMessageList(errorMesages);
} else {
res.setStatus("SUCCESS");
}
return res;
}
My bean object
public class UserRegister {
@NotEmpty @NotNull
private String username;
@NotEmpty @NotNull
private String password;
@NotEmpty @Email @NotNull
private String emailAddress;
setter and getters....
}
Do i need to do any other configuration or something else to get it validated properly?
app-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">
<context:property-placeholder location="classpath:database.properties" />
<context:component-scan base-package="com.app" />
<tx:annotation-driven transaction-manager="hibernateTransactionManager"/>
<bean id="myAuthenticationSuccessHandler" class="com.app.security.handler.MySimpleUrlAuthenticationSuccessHandler" />
<bean id="myAuthenticationFailureHandler" class="com.app.security.handler.MySimpleUrlAuthenticationFailureHandler" />
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.user}" />
<property name="password" value="${database.password}" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
</props>
</property>
</bean>
<!-- bind your messages.properties
<bean class="org.springframework.context.support.ResourceBundleMessageSource"
id="messageSource">
<property name="basename" value="messages" />
</bean>
-->
</beans>
Is the userReg model object with the attributes (username, email etc) fields getting submitted to the server?
If not, The form fields may not be getting bound correctly to the model object
Try
<form:form action="register" method="post" commandName="userRegister">
Also, the input fields needs to have the mapping to the model object
<form:input path="username" />
Also ensure that is set in the context file
<mvc:annotation-driven />
Here is a demo : http://www.codejava.net/frameworks/spring/spring-mvc-form-validation-example-with-bean-validation-api
Also confirm that the validator jars are present in pom.xml
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
or
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.0.1.Final</version>
</dependency>
Can you please list the spring xml configuration file (the file that has the below line in it)?
<mvc:annotation-driven />
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.