Java Bean Validation用于long类型。

huangapple go评论70阅读模式
英文:

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 &quot;&quot;;

	Class&lt;?&gt;[] groups() default {};

	Class&lt;? extends Payload&gt;[] payload() default {};

}

My NotNullNumberValidator class

class NotNullNumberValidator implements ConstraintValidator&lt;NotNullNumber, Number&gt; {

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

Use of the Anootation

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

@NotNullNumber(message = &quot;message for long validation&quot;)
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

huangapple
  • 本文由 发表于 2020年8月14日 07:52:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/63404699.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定