1

I have the following situation in a Spring project: we have a bunch of user forms and they need to be validated only on demand. For example, let's say I have a class SomeUserData

class SomeUserData {
   //@NotNull
   private String firstName;

   //@NotNull
   //@Min(18)
   //@Max(100)
   private Integer age;
}

I need to be able to save any data the user enters, even if he leaves a name empty or puts 15 for age without generating any warnings.

But I do need to run data through validation when the user requests such validation.

Does anybody know a way to solve this issue? Let me know if I haven't provided enough details.

Kabachok
  • 573
  • 1
  • 7
  • 22
  • Why doesn't the validity of the data matter before the user requests it? – Kayaman Jul 02 '18 at 12:17
  • @Kayaman Business requirement. It is requested to save every input without validation and to have a specific action to validate. So basically you can save a draft version even if it is full of mistakes and diagnose it when you are ready. – Kabachok Jul 02 '18 at 12:19

3 Answers3

0

I would recommend to have different classes for this purpose: SomeUserData and SomeUserDataStrict. Moreover, you can have different validation sets like maturity rating (like Motion Pricture Association of America film rating system): SomeDataG, SomeDataPG, SomeDataPG13, SomeDataR, SomeDataNC17

Pavel
  • 2,557
  • 1
  • 23
  • 19
0

Write custom validator and for example, validate method of that validator have a optional boolean parameter for example "validateBusiness". If that parameter is present and setted to TRUE than perform validations, otherwise save entity without validation.

nick79
  • 417
  • 3
  • 7
0

To validate conditionally your class object, You can add a field Let say validateOnDemand boolean field to your class.

class SomeUserData {
   private String firstName;
   private Integer age;
   private boolean validateOnDemand;

}

And then use @AssertTrue on method which will have your conditional validation logic

@AssertTrue
public boolean validateFirstNameOnDemand() {
   if(this.validateOnDemand){
      // your logic to validate/invalidate 
   }else{
     return true; // validate 
   }
}

If the above method return true the request object is validated other wise if return false, it will throw a AssertionException with message if passed in @AssertTrue parameter

Ajit Soman
  • 3,926
  • 3
  • 22
  • 41