1

The gender validation is not working. Even if no values are entered in the gender text field, the form is getting validated successfully without throwing any error.

Below is the Employee class:

@Size(min=2,max=10)
private String gender;

// Setters and Getters

Below is the Controller method:

@RequestMapping(value="done", method = RequestMethod.POST)
public String validateForm(@Valid Employee employee, BindingResult result, ModelMap m){
    if(result.hasErrors()){
        System.out.println("Validation Failed!!!");
        return "main";
    }else{
        System.out.println("Validation Succeeded!!!");
        return "done";
    }
}

Below is the context file:

<context:annotation-config />
<context:component-scan
    base-package="com.XXX" />

<bean id="viewResolver"
    class="org.springframework.web.servlet.view.UrlBasedViewResolver">
    <property name="viewClass"
        value="org.springframework.web.servlet.view.JstlView" />
    <property name="prefix" value="/WEB-INF/pages/" />
    <property name="suffix" value=".jsp" />
</bean>

Below is the jsp file:

<tr>
            <td>
                Gender:
            </td>
            <td>
                <form:input path="gender"/>
                <form:errors path="gender" cssStyle="color: red;"/>
            </td>
        </tr>

I am not able to find out whats missing but its something silly. Please help.

2
  • Is HibernateValidator on your classpath? Did you import @Size from the javax.validation package? Commented May 8, 2014 at 17:32
  • Both the validators: validation-api.jar and hibernate-validator.jar are present in my classpath. Yes, the package is: import javax.validation.constraints.Size; Commented May 8, 2014 at 17:34

1 Answer 1

3

1) All of the javax constraints include an implicit "or null" in their pass conditions. If you want to catch blanks you need to either add @NotNull, or reconfigure the web binder to bind blank inputs to empty string instead of null.

2) <context:annotation-config /> does not turn on Spring 3 dispatcher servlet auto-config magic. You need to define your own validator bean if you do that. To enable everything to automagically work you need to use <mvc:annotation-driven />.

Sign up to request clarification or add additional context in comments.

9 Comments

I changed the @Size to @NotNull but still the validation does not work. Please advice.
You need both annotations
Still this does not work: @Size(min=2,max=10) @NotNull private String gender;
Does validation work for strings of length 1 or 11 and not work for blanks, or nothing works?
Nothing works. First, tried without any characters, second: tried with a single character.
|

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.