Compare two fields that use same class

后端 未结 1 530
悲&欢浪女
悲&欢浪女 2020-12-21 23:47

I have two input fields fromDate and toDate which are instances of Date class. The Date class uses custom Date validator which validates the month, day and year fields cont

相关标签:
1条回答
  • 2020-12-22 00:20

    Yes, you can! Suppose you have the following PrimeFaces's input fields:

    <p:calendar id="from" value="#{mrBean.fromDate}" binding="#{from}" >
       <p:ajax process="from to" update="toDateMsg" />
    </p:calendar>
    <p:calendar id="to"   value="#{mrBean.toDate}" >
       <f:attribute name="fromDate" value="#{from.value}" />
       <f:validator validatorId="validator.dateRangeValidator" />
       <p:ajax process="from to" update="toDateMsg" />
    </p:calendar>
    <p:message for="to" id="toDateMsg" />
    

    This should be your Validator:

    @FacesValidator("validator.dateRangeValidator")
    public class DateRangeValidator implements Validator {
    
        @Override
        public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
            if (value == null || component.getAttributes().get("fromDate") == null) return;
    
            Date toDate   = (Date) value; 
            Date fromDate = (Date) component.getAttributes().get("fromDate");
    
            if (toDate.after(fromDate)) {
                FacesMessage message = new FacesMessage("Invalid dates submitted.");
                message.setSeverity(FacesMessage.SEVERITY_ERROR);
                throw new ValidatorException(message);
            }
        }
    }
    

    Note that I am using PrimeFaces's <p:calendar> component to write my example because the properties binded to this component will automatically be converted to Date object before being validated. In your program, you may have your own Converter to convert String to Date.

    0 讨论(0)
提交回复
热议问题