Search code examples
javahibernatevalidationhibernate-validator

Is Hibernate Validator @NotNull always triggered first?


In other words if I have two constraints like @Email and @NotNull the @Email validator won't throw a NPE?

It seems obvious but I'm asking because I saw that some custom validators check whether the value to be validated is null and return true if it is. This seems like a bad idea because if the developer forgot to add @NotNull to the email field, then the email field will still pass validation.

TIA, Ole


Solution

  • Returning true for null is considered best practice in Bean Validation and all built-in constraints adhere to it (where possible). The Bean Validation spec says in section 3.4. Constraint validation implementation:

    While not mandatory, it is considered a good practice to split the core constraint validation from the not null constraint validation (for example, an @Email constraint will return true on a null object, i.e. will not take care of the @NotNull validation).

    null can have multiple meanings but is commonly used to express that a value does not make sense, is not available or is simply unknown. Those constraints on the value are orthogonal in most cases to other constraints. For example a String, if present, must be an email but can be null. Separating both concerns is a good practice.