Validating a POST request is very easy. Just register a validator in the usual Spring way. Spring-Json View adds any errors as a field name : error message pair to a fielderrors array in the response Json object.
Write your validator class by implementing the Validator interface.
public class SpringJsonValidator implements Validator {
public void validate(Object obj, Errors errors) {
SpringJsonForm form = (SpringJsonForm) obj;
if (form.getPlaceofbirth() == null || "".equals(form.getPlaceofbirth())) {
errors.rejectValue("placeofbirth", "error.no.placeofbirth", null, "Placeofbirth required.");
}
}
@Override
public boolean supports(Class clazz) {
return SpringJsonForm.class.equals(clazz);
}
}
Configure the SimpleFormController by adding the validator.
<beans>
<bean name="simpleJsonPostFormController"
class="org.thing.spring.json.controller.SimpleJsonPostFormController">
<property name="commandClass">
<value>org.thing.spring.json.controller.SpringJsonForm</value>
</property>
<property name="formView"><value>jsonView</value></property>
<property name="successView"><value>jsonView</value></property>
<property name="validator"><ref bean="validator"/></property>
</bean>
<bean name="validator" class="org.thing.spring.json.controller.SpringJsonValidator"/>
</beans>
Spring-Json View adds fielderrors to the Json response.
{"command":{
"birthday":"08-02-2008",
"placeofbirth":""
},
"failure":"true",
"hasGlobalErrors":"false",
"hasFieldErrors":"true",
"fielderrors":{
"placeofbirth":"Please enter a a place of birth!"
}}