简体   繁体   中英

Java Bean Validation for long type

I can't find a way to validate when a long variable comes with null value. I have to validate BigDecimal and long variables, for BigDecimal my custom annotation works fine, but for long type doesn't work. I'm using the Number class to wrap the incomming type and validate the value.

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = NotNullNumberValidator.class)
@Documented
public @interface NotNullNumber {

    String message() default "";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

}

My NotNullNumberValidator class

class NotNullNumberValidator implements ConstraintValidator<NotNullNumber, Number> {

    @Override
    public boolean isValid(Number value, ConstraintValidatorContext context) {
        return value != null;
    }
}

Use of the Anootation

@NotNullNumber(message = "message for BigDecimal validation")
private BigDecimal subtotal; //works fine

@NotNullNumber(message = "message for long validation")
private long fechaPago;// not working}

Am I in the rigth way or there is another way to do this? @NotNull annotation doesn't make the job.

EDIT: I am using this validation with a @RequestBody, I want to validate if the JSON field (long) fechaPago is present in the request body. I know that with the wrapper class Long works, but I can't change the variable type (the rules are the rules here).

I see you're using primitive long which has no idea of nulls, the validator should work fine if you convert it to the wrapper

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM