This question already has an answer here:
- Spring3 MVC: Validation not working 1 answer
I am new to Spring 3 MVC and was trying to implemnt ConstrainValidation
following this but the validation part did not worked, the isValid
method did not got invoked. Not sure if I am missing something in my configuration, below is what I tried:
Employee.java
public class Employee {
@Phone
private String phone;
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
Phone.java
@Documented
@Constraint(validatedBy = {PhoneValidator.class})
@Target( { ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Phone {
String message() default "{Phone}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
PhoneValidator.java
public class PhoneValidator implements ConstraintValidator<Phone, String>{
@Override
public void initialize(Phone phone) {
// TODO Auto-generated method stub
}
@Override
public boolean isValid(String phoneField, ConstraintValidatorContext cxt) {
if(phoneField == null) {
return false;
}
return phoneField.matches("[0-9()-\\.]*");
}
}
Controller
@RequestMapping(value="done")
public String displaySuccess(@Valid Employee employee,BindingResult result,Model model){
if(result.hasErrors()){
System.out.println("Validation Failed!!!");
return "display";
}else{
System.out.println("Validation Succeeded!!!");
return "done";
}
}
Context.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
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">
<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>
</beans>
Can someone please point out what am I missing? The Phone
validation is not working, the isValid
method is also not getting invoked.
Changing
<context:annotation-config />
to<mvc:annotation-driven />
resoled my problem.Reference:
Spring3 MVC: Validation not working