Javax empty integer field validation

Viewed 18021

My app uses javax validation for the salary field, which is int. With what annotation should I use it, to avoid the error message like that

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

My current implementation looks like this:

@Column(name = "salary", nullable = false)
@NotNull(message= "salary may not be empty")
@Range(min = 1)
private int salary;

I know that I can not use NotBlank for a int field, that leads to an error. How can I display the message "salary may not be empty" instead of the exception above, if the "string" is empty? Thanks

4 Answers

I suggest you to use the object type Integer which can hold the null value itself.

@Column(name = "salary", nullable = false)
@NotNull(message= "salary may not be empty")
@Range(min = 1)
private Integer salary;

The above secures there will be always the salary input that has a value and it's equal or greater than 1.

Set this to your web deployment descriptor file, web.xml:

<context-param>
    <param-name>
        javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL
    </param-name>
    <param-value>true</param-value>
</context-param>

If that field is included in another class, such as:

public static class Employee {
    @Column(name = "salary", nullable = false)
    @NotNull(message= "salary may not be empty")
    @Range(min = 1)
    private int salary;
}

You also need to make sure use @Valid for instances of Employee:

@Valid @NotNull
public Employee someEmployee;
@Column(name = "salary", nullable = false)
@Range(min = 1, message= "salary may not be empty or null")
private int salary;

In @Range we can also mention message. It means salary will be 1 or greater than 1 it will not null or empty.

Related