1

I came across a scenario where I have two fields, for example CA and ID fields, where I need to add a simple check to ensure that both CA and ID cannot be null, and should throw an error message like 400 bad request. However, when one field is null but the other is not, for example when ID is NULL and CA field has some value, then it should be able to process the request, and it should send 200 ok for the request.

Can anyone please suggest a validation method for this kind of scenario.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
amith
  • 11
  • 1

1 Answers1

0

Assume you have a model like this:

public class Testmodel {

@NotNull(message = "MUST NOT BE NULL")
private int CA;

@NotNull(message = "MUST NOT BE NULL")
private int ID;

public Testmodel(@NotNull(message = "MUST NOT BE NULL") int CA, @NotNull(message = "MUST NOT BE NULL") int ID) {
    this.CA = CA;
    this.ID = ID;
}

public Testmodel() {
}

public int getCA() {
    return CA;
}

public void setCA(int CA) {
    this.CA = CA;
}

public int getID() {
    return ID;
}

public void setID(int ID) {
    this.ID = ID;
}}

Then you in your to validate the two fields you would need to do something like this:

import javax.validation.Validator;

private final Validator validator;

@Autowired
public YourClass(Validator validator) {
        this.validator = validator;
}

HttpStatus testValidation() {
        Testmodel testmodel = new Testmodel();
        Set<ConstraintViolation<Testmodel>> violations = validator.validate(testmodel);
    if (violations.isEmpty()) {
        return HttpStatus.OK;
    } else {
        Map<String, Object> data = handleConstraintViolations(violations);
        return HttpStatus.BAD_REQUEST;
    }
}

private Map<String, Object> handleConstraintViolations(Set<ConstraintViolation<Testmodel>> violationsList) {
    Map<String, Object> data = new HashMap<>();

    for (ConstraintViolation<?> violation : violationsList) {
        data.put(violation.getPropertyPath().toString(), violation.getMessage());
    }

    CustomValidationException ce = new CustomValidationException("Invalid fields!", data);
    return data;
}

Also make sure you have the javax validation dependency in your pom file

    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
        <version>2.0.0.Final</version>
    </dependency>
Alexandros Kourtis
  • 539
  • 2
  • 6
  • 20