0

I want to validate different properties of object based on the occasion. For an example lets say I have a User object

public class User{
    private String username;
    private String password;
    private String age;
}

When adding a user I want to validate all fields. But when user reset a password there would be username and password. If Spring validator tries to validate age as well it'll be a failure.

Is there a way that I can tell Spring validator to only validate a certain subset of object properties.

Susitha Ravinda Senarath
  • 1,648
  • 2
  • 27
  • 49
  • 2
    You can use JSR-303 validation annotations combined with Spring's [`Validated`](http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/validation/annotation/Validated.html) annotation which allows you to specify validation groups. – Bohuslav Burghardt Jul 11 '15 at 07:37

1 Answers1

1
  1. To partially update an entity, you should use @SessionAttributes to store the model in session between requests. You could use hidden form fields, but session is more secure.

  2. To secure fields use webDataBinder.setAllowedFields("field1","field2",...) or create a class specific to the form then copy values to your entity.

  3. Use Validation Groups + @Validated. Though in this case it might just be easier to use separate Form Backing Objects.

See my answer here: Spring MVC: Validation, Post-Redirect-Get, Partial Updates, Optimistic Concurrency, Field Security

Community
  • 1
  • 1
Neil McGuigan
  • 46,580
  • 12
  • 123
  • 152