'spring validator @Pattern doesn't work on Integer

I am trying a simple pattern validation:

@Min(value = 0, message = "invalid.amount")
@Pattern(regexp = "[0-9]+", message = "invalid.amount")
private double amount;

But it gives the error like:

org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.throwExceptionForNullValidator(ConstraintTree.java:229)

But this works perfectly fine:

@Pattern(regexp = "[\\w|-]{1,5}")
private String data;

It seems regex doesn't work on number types.



Solution 1:[1]

You are assuming that the @Pattern annotation will return true if a substring regex match passes. If it isn't working then your assumption may not be true.

@Pattern(regex=,flag=) CharSequence

Checks if the annotated string matches the regular expression regex considering the given flag match.

You can try change double to String and works with @Pattern normally.

@Pattern(regexp = "[0-9]+", message = "invalid.amount")
private String amount;

Also other way could be:

@DecimalMax("10.0") @DecimalMin("0.0") 
private double amount;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1