'hibernate @Length and @Size used along with String type in java dto but String type filed allow all other types like boolean and integer etc
I used @Length and @Size of Hibernate annotations along with String type in java DTO class but String type filed allow all other types like boolean and integer ..etc.
So how to restrict only string type data along with @Length or @Size with message.
@Data
@AllArgsConstructor
@NoArgsConstructor
public class CreateRoleRequestDto extends BaseDto {
@Size(max = 255, message = "Role description field length should not exceed 255
characters"
private String description;
@Length( max = 50,message = "Role name should not exceed 50 characters")
private String displayName;
}
So here dispalyName and description allow boolean and integer etc . how to restrict to allow only string type along with @Length and @Size with message .
Solution 1:[1]
You need to use regxp for solving the issue. Suppose, If you are willing to take only alphabet for the string then you can use something like this :
@Size(max = 255, message = "Role description field length should not exceed 255
characters"
@Pattern(regexp="^[A-Za-z]*$",message = "Invalid Input")
private String description;
Like this is you need anything more than just alphabet you can write your custom regexp base on your need.
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 | Amimul Ehsan Rahi |
