How to add validations to request class during submit operation only in service side

49 views Asked by At

I have got a requirement in my project to add validations to my request class only during submit operation. During save operation no empty field validations is expected. Now I know 2 ways to validate request class.

  1. Using @NotBlank annotations in your request class for the respective field. But I cannot use this way since my requirement is specific to submit operation. And for both save and submit I am using the same request class.
  2. Using message.properties file, where I can define the errors and use them in my validator class e.g.:

Validator.java

private void validateIncidentDetails(CreateIncidentRequest request) {
...
if(checkForNullOrEmpty(request.getDetectionDate())) {
            String msg = messageBundleService.fetchMessage("ERR_EMPTY_DETECTION_DATE");
            throw new BadRequestException(msg);
        }
---
}

**Likewise for every field.

errorMessage.properties

ERR_EMPTY_DETECTION_DATE=Detection Date is required

Now my question is, Is there any other better ways to implement the above requirement.

1

There are 1 answers

0
MostlyJava On

You can try this way to check for null

public boolean checkNull() throws IllegalAccessException {
    for (Field f : getClass().getDeclaredFields())
         f.setAccessible(true);//to access private property
        if (f.get(this) != null)
            return false;
    return true;            
}