1

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">&times;</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>

1 Answer 1

1

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 />
Sign up to request clarification or add additional context in comments.

17 Comments

getting exception: ERROR [org.springframework.web.servlet.tags.form.InputTag] (http-localhost-127.0.0.1-8080-1) Neither BindingResult nor plain target object for bean name 'userRegister' available as request attribute: java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'userRegister' available as request attribute
withut form:form tag also, i was able to see the values inside the userreg object..in my controller
it seems more to me that spring is not picking up your notempty and notnull annotation. hibernate validator is present in your pom right? Also, try setting min and max size through annotaiton @size and see if validators pick errors on size. Atleast, we will know if validators kick in at all.
it seems more to me that spring is not picking up your notempty and notnull annotation. hibernate validator is present in your pom right? Also, try setting min and max size through annotaiton @size and see if validators pick errors on size. Atleast, we will know if validators kick in at all. Try this and see if min size and max size gets picked up by the error
HI saurabh, here is a good tutorial that explains this in detail. journaldev.com/3524/… Hope this helps.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.