Compare two fields that use the same class

I have two input fields fromDate and toDate, which are instances of the Date class. The Date class uses a custom date validator that validates the month, day, and year fields contained in a date field. A custom date validator is defined for each date ie, fromDate and toDate. I need to compare month, day or year fields fromDate with toDate. If fromDate is greater than toDate, a validation message should be displayed.

Update:

FromDate and toDate are two custom date components listed below

<eg:dateField id="inpFromDate" value="#{mrBean.fromDate}" .... />
<eg:dateField id="inpToDate" value="#{mrBean.toDate}" .... />

      

fromDate and toDate are instances of the Date class, which is

public class Date {
private String mm;
private String dd;
@customDateValidator   //Validates each date field
private String yyyy;
//constructors
//getters and setters

      

How would you implement a validator in this case when there is already a validator in each date

+1


source to share


1 answer


Yes, you can! Suppose you have the following PrimeFaces 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 yours 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 the PrimeFaces component <p:calendar>

to record my example, because the properties bound to this component will automatically be converted to an object Date

before validation. In your program, you can have your own Converter

to convert String

to Date

.

+6


source







All Articles