Is there a 'must be numerical' validation-notation for fields in Spring boot?

Viewed 708

I am currently beginning to learn about Spring boot, and how to use the build in validation tools(anotation) in an class' fields. I know how to validate a String and set a field to @NotNull, but cant find any way to do the same with a numerical value. I thought about using @Pattern for regex but hoped there was something more clear(and easier) to use.

I do not want to set a @Min or @Max. It should be able to use all possible numerical int values.

Current code, where i want to set the notation at zipCode(the last field)

@Entity
public class Customer {
    @Id
    private int id;
    @NotNull
    @Size(min=2,max=15)
    private String firstName;
    @NotNull
    @Size(min=2,max=15)
    private String lastName;
    @NotNull
    @Size(min=5,max=45)
    private String address;
    @NotNull
    @Size(min=1,max=15)
    private String driversLicense;
    @NotNull
    @Size(min=1, max=3)
    private String licensesType;
    @NotNull
    @Size(min=1,max=30)
    private String phone;
    @NotNull
    @Size(min=1,max=15)
    private String nationality;
    @NotNull
    @Size(min=1,max=30)
    private String city;
    @NotNull
    private int zipCode;

With the @NotNull notation, the error message I get is

Failed to convert property value of type java.lang.String to required type int for property zipCode;
nested exception is java.lang.NumberFormatException: For input string:"xx"

and want it to be a custome error message, but when i do

@NotNull(message="Custom error message") 
private int zipCode

I still get the above error message instead.

Any ideas to fix these two problems, would be much appreciated

edit: did not realise that there could only be one "approved" answer to this question. As it's two questions in one, both @Pankaj and @JArgente helped with great answers

2 Answers

The problem you have is that this error is produced before the validation, in the deserealization phase, I mean first of all spring tries to convert the input json to the types you have specify in your class and then validate the input to ensure that the constraints are fullfilled, (for example a string is between the boundaries specified by size.. etc).

So the way to customize the message you want is to create a custom deserializator or mark that attribute as String and check yourself that it store a valid number or not and then use the custom message if not.

You can use @Positive annotation as

  @Positive
  private int zipCode;

From Documentation of @Positive

The annotated element must be a strictly positive number (i.e. 0 is considered as an invalid value). Supported types are:

  • BigDecimal
  • BigInteger
  • byte, short, int, long, float, double and their respective wrappers

null elements are considered valid.

Related