英文:
Java Bean Validation for long type
问题
无法找到验证长变量是否为null值的方法。我必须验证BigDecimal和long变量,对于BigDecimal,我的自定义注释正常工作,但对于long类型不起作用。我正在使用Number类来包装传入的类型并验证该值。
@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 {};
}
我的 NotNullNumberValidator
类
class NotNullNumberValidator implements ConstraintValidator<NotNullNumber, Number> {
@Override
public boolean isValid(Number value, ConstraintValidatorContext context) {
return value != null;
}
}
注解的使用
@NotNullNumber(message = "message for BigDecimal validation")
private BigDecimal subtotal; //正常工作
@NotNullNumber(message = "message for long validation")
private long fechaPago;// 不起作用
我是否走在正确的路上,还是还有其他方法可以实现这个?@NotNull
注解无法完成这项工作。
编辑: 我正在使用此验证与 @RequestBody
一起使用,我希望验证JSON字段(long) fechaPago 是否存在于请求体中。我知道使用包装类Long可以工作,但我不能更改变量类型(规则就是规则)。
英文:
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).
答案1
得分: 4
我看到你正在使用原始的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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论