Java Springboot中长类型变量的@NotZero注释

时间:2018-09-17 15:56:33

标签: java validation spring-boot annotations spring-annotations

我正在尝试为@NotZerolong类型的变量构建一个float注释。对于具有非零约束的字符串,这应该类似于@NotBlank

我尝试使用@Min@Numeric批注,但这些不足以满足我的要求。在这种情况下,如果不是字符串,则正则表达式似乎没有任何帮助。我该如何添加一个自定义函数来检查输入数字是否为零,并将其用作注释。

我的电话号码可以采用0.001、25、36.25等值,例如任何严格的longfloat正值。

1 个答案:

答案 0 :(得分:1)

如果您使用的是休眠模式,请考虑使用自定义验证程序:https://www.baeldung.com/spring-mvc-custom-validator

注释定义:

@Documented
@Constraint(validatedBy = NonZeroFloatValidator.class)
@Target( { ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface NonZeroFloatConstraint {
    String message() default "Float value is zero";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

验证器逻辑:

public class NonZeroFloatValidator implements ConstraintValidator<NonZeroFloatConstraint, Float>
{    
    @Override
    public void initialize(NonZeroFloatConstraint cons) {}

    @Override
    public boolean isValid(Float f, ConstraintValidatorContext cxt)
    {
        return Float.compare(f, 0.0f) != 0;
    }
}

您可能需要另一个约束来限制双打,但是模式是相同的。

相关问题