disallowed field validation

java, spring-mvc, validation

Solution

There are no good ways to do it.

JSR-303 offers two approaches for selective validation:

- You may validate specific properties by calling `validator.validateProperty(news, "content")`

You may define validation groups:

@Size(max=255, groups = {Default.class, WebValidation.class})      
String content; 

And validate the specified group: `validator.validate(news, WebValidation.class);`

None of these approaches are directly supported by Spring MVC. You can autowire a JSR-303 `Validator` and call these methods manually, but they return `Set<ConstraintViolation<?>>`, and the code for putting these `ConstraintViolation`s into `BindingResult` is buried deep inside the Spring internals and can't be easily reused (see `SpringValidatorAdapter`).

There is a feature request for supporting validation groups in `@Valid`-style approach (SPR-6373) with fix version 3.1.

So, aside from creating a special DTO class, you doesn't have many options: you can use manual validation (without JSR-303), or you can copy-paste the code from `SpringValidatorAdapter` into your own utility method and manually call the methods of JSR-303 `Validator`.

Problem

I'm new with spring framework. I'm currently building some news manager form. Here a sample of my news entity : ``` class News { @NotNull long id; @NotNull long idAuthor; @Size(max=255) String content; } ``` As you can see, I use JSR303 annotation validation with Spring. I want to validate my "news edit form". ``` @RequestMapping( value = "/edit" , method = RequestMethod.POST) public String editAction(@Valid @ModelAttribute News news, BindingResult result) { System.err.println(result.hasErrors()); ... return "editView"; } ``` Define allowed field : ``` //initBinder function : binder.setAllowedFields("content"); ``` Well, i'm trying to validate only "content" field (allowed field set on my binder)... But Spring always validate all the field defined on my entity (so "id" & "idAuthor" return error) How can i only validate allowed field (set on initBinder function) ?

Original source