We have the validate()
method directly available in our action classes in which we can put our own logic to perform some kind of validations we need.
For example, if I need to validate two fields regarding date-time, I can put my own logic in the validate()
method something like the following.
public final class DiscountAction extends ActionSupport implements ValidationAware, ModelDriven<Discount>
{
private Discount entity=new Discount();
@Override
public Discount getModel() {
return entity;
}
@Override
public void validate()
{
if(entity.getDiscountStartDate()!=null&&entity.getDiscountEndDate()!=null)
{
final int period=30;
final DateTime startDate=entity.getDiscountStartDate().withZone(DateTimeZone.forID("Asia/Kolkata")).withMillisOfSecond(0);
final DateTime endDate=entity.getDiscountEndDate().withZone(DateTimeZone.forID("Asia/Kolkata")).withMillisOfSecond(0);
final DateTime currentDate=new DateTime(DateTimeZone.forID("Asia/Kolkata"));
final int daysBetween = Days.daysBetween(startDate, endDate).getDays();
if(startDate.isAfter(endDate))
{
addFieldError("discountStartDate", "The start date must be earlier than the end date.");
}
else if(startDate.equals(endDate))
{
addFieldError("discountEndDate", "Both the dates can not be same.");
}
else if(DateTimeComparator.getDateOnlyInstance().compare(currentDate, endDate)==0 || endDate.isBefore(currentDate))
{
addFieldError("discountEndDate", "Can not be today's date or any day before today.");
}
else if(Days.daysBetween(startDate, endDate).getDays()<1)
{
addFieldError("discountEndDate", "There must be an interval of at least one day.");
}
else if(daysBetween>period)
{
addFieldError("discountEndDate", "The discount period is valid only upto "+period+(period==1?" day":" days")+" period which it excceds. The actual difference is "+daysBetween);
}
}
}
}
Assuming entity
is an instance of the model class.
Why do we need a custom validator here? I have not yet tried a custom validator, since it is not needed yet.
Could you please show me a real situation/example where a custom validator is precisely need?