简体   繁体   English

Java 长类型的 Bean 验证

[英]Java Bean Validation for long type

I can't find a way to validate when a long variable comes with null value.当长变量带有 null 值时,我找不到验证方法。 I have to validate BigDecimal and long variables, for BigDecimal my custom annotation works fine, but for long type doesn't work.我必须验证 BigDecimal 和 long 变量,对于 BigDecimal,我的自定义注释工作正常,但对于 long 类型不起作用。 I'm using the Number class to wrap the incomming type and validate the value.我使用数字 class 来包装传入类型并验证值。

@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我的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. @NotNull注释不能完成这项工作。

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.编辑:我将此验证与@RequestBody 一起使用,我想验证请求正文中是否存在 JSON 字段(长)fechaPago。 I know that with the wrapper class Long works, but I can't change the variable type (the rules are the rules here).我知道使用包装器 class Long 可以工作,但我无法更改变量类型(规则是这里的规则)。

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我看到您使用的是不知道空值的原始 long,如果您将其转换为包装器,验证器应该可以正常工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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