0

I have a form in which :

  1. firstname and lastname are mandatory fields for registered user.
  2. ssn for new user.
  3. contract number for owner.

So, on clicking the submit button, REST API (connect API) is called with values from either of the above groups.


My bean class has members :

  1. FN
  2. LN
  3. SSN
  4. contractNum

How do I validate using bean/hibernate validator and identify which group has been passed ?

Anish B.
  • 9,111
  • 3
  • 21
  • 41
Nidhya
  • 1
  • 1

2 Answers2

0

From the Hibernate Documentation, you can read for detail

https://hibernate.org/validator/

Hibernate Validator allows to express and validate application constraints. The default metadata source are annotations, with the ability to override and extend through the use of XML. It is not tied to a specific application tier or programming model and is available for both server and client application programming. But a simple example says more than 1000 words:

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

public class User {

   @NotNull
   private String firstName;

   @NotNull
   private String lastName;

   @NotNull
   private String ssn;


}
Anil
  • 364
  • 3
  • 15
  • All the four fields shouldnt be not null at a time! My validator has to dynamically check the group fields! Say for example, either firstname amd lastname should be ‘not null’ OR ssn should be ‘not null’ OR contract should be ‘not null’. How do i do that? – Nidhya Sep 22 '19 at 13:37
0

Bean Validation is best used for simple validation logic. If your validation requires more complexity, use Spring's Validator interface instead.

I don't know the context domain, so I'll just call your bean "Form" with all String fields for the example:

public class Form {

    private String firstName;

    private String lastName;

    private String ssn;

    private String contractNumber;

   // getters and setters
}

Then create a validator for this class:

public class FormValidator implements Validator {

    public boolean supports(Class clazz) {
        return Form.class.isAssignableFrom(clazz);
    }

    public void validate(Object target, Errors errors) {
        Form form = (Form) target;

        // validation logic
    }
}

Then you can simply use it like this:

Form form = ...;
Validator validator = new FormValidator();
Errors errors = new Errors();

validator.validate(form, errors);

if (errors.hasErrors() {
    // not valid
} else {
    // is valid
}
Sync
  • 3,571
  • 23
  • 30