I am using Hibernate validator like @NotEmpty to see if a specific property in a class is empty or not. The class is as as shown:
@Entity
@Table(name="emergency_messages")
public class EmergencyMessages implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id", nullable=false)
private Integer id;
@NotEmpty(message="Home message cannot be empty")
@Column(name="home_page_message")
private String homePageMessage;
@Range(min=0, max=1, message="Please select one of the display announcement value")
@Column(name="messages_enabled")
private Integer messagesEnabled;
}
So far so good. Whenever the property “homePageMessage” is empty I can see that the correct error message in the form in the browser.
Now the situation has changed. The new requirement is that the property “homePageMessage” can be empty only if the other property “messagesEnabled” is set to 1. If it is set to 0 then there should be no empty check done for “homePageMessage”. In simple words the validation of “homePageMessage” should now be dependent on the “messagesEnabled” value.
My question: Is this possible to do with annotations? If not, then I will have to dismantle my hibernate validator mechanism and create my own validation class.
Following is the code that I came up with (after suggestions from Ajinkya and Alex):
Customized Annotation:
Customized Validator:
Usage of customized annotation in the code:
I hope it helps someone.