Search code examples
javavalidationspring-bootannotationsspring-annotations

@NotZero Annotation for long type variable in Java Springboot


I am trying to build a @NotZero annotation for long & float type variables. This should work like @NotBlank for strings with non-zero constraints.

I have tried @Min and @Numeric annotation but these do not suffice my requirement. Regex doesn't seem to be of any help in this case not being a string. How can I add a custom function which checks if the input number is not zero and use that as annotation.

My number can take values like 0.001, 25, 36.25 etc. any strictly positive long & float values.


Solution

  • If you're using hibernate, consider a custom validator: https://www.baeldung.com/spring-mvc-custom-validator

    The annotation definition:

    @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 {};
    }
    

    The validator logic:

    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;
        }
    }
    

    You would need another constraint for doubles, but the pattern is the same.