17

我想比较两个日期(StartDate 和 EndDate)并检查一个是否在另一个之前。最简单的解决方案是在 backing bean 上执行此操作并“短路”该方法。

但是,此验证不会与其他表单验证同时发生。例如,如果我有另一个需要验证的字段(除了日期)并且输入无效,我只会收到该特定字段的消息。只有当其他字段有效时,我才会根据支持 bean 获得日期验证。

有人有解决方案吗?

4

4 回答 4

36

但是,此验证不会与其他表单验证同时发生。

支持 bean 操作方法确实不打算执行输入验证。


有人有解决方案吗?

为工作使用正确的工具;使用正常的Validator.

@FacesValidator("dataRangeValidator")
public class DateRangeValidator implements Validator {
    // ...
}

反过来,使用单个验证器验证多个输入值确实是另一回事。基本上,您应该将其他组件或其值获取/传递到validate()方法实现中。以最简单的形式,您可以使用<f:attribute>它。假设您<p:calendar>用来选择日期,这里有一个具体的启动示例:

<p:calendar id="startDate" binding="#{startDateComponent}" value="#{bean.startDate}" pattern="MM/dd/yyyy" required="true" />
<p:calendar id="endDate" value="#{bean.endDate}" pattern="MM/dd/yyyy" required="true">
    <f:validator validatorId="dateRangeValidator" />
    <f:attribute name="startDateComponent" value="#{startDateComponent}" />
</p:calendar>

(注意binding属性,它使组件在 EL 范围内完全可用给定的变量名;还请注意,这个例子是原样的,你绝对不应该将它绑定到 bean 属性!)

dateRangeValidator看起来像这样的地方:

@FacesValidator("dateRangeValidator")
public class DateRangeValidator implements Validator {

    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        if (value == null) {
            return; // Let required="true" handle.
        }

        UIInput startDateComponent = (UIInput) component.getAttributes().get("startDateComponent");

        if (!startDateComponent.isValid()) {
            return; // Already invalidated. Don't care about it then.
        }

        Date startDate = (Date) startDateComponent.getValue();

        if (startDate == null) {
            return; // Let required="true" handle.
        }

        Date endDate = (Date) value;

        if (startDate.after(endDate)) {
            startDateComponent.setValid(false);
            throw new ValidatorException(new FacesMessage(
                FacesMessage.SEVERITY_ERROR, "Start date may not be after end date.", null));
        }
    }

}

如果您碰巧使用JSF 实用程序库 OmniFaces,那么您也可以只使用它的<o:validateOrder>组件。无需自定义验证器即可实现以下要求:

<p:calendar id="startDate" value="#{bean.startDate}" pattern="MM/dd/yyyy" required="true" />
<p:calendar id="endDate" value="#{bean.endDate}" pattern="MM/dd/yyyy" required="true" />
<o:validateOrder components="startDate endDate" />

也可以看看:

于 2013-09-30T13:13:16.937 回答
6

如果您使用可以限制最小和最大日期的 PrimeFaces。用户无法选择更大的范围这是一个示例:

<p:calendar id="startDate" value="#{bean.startDate}" maxdate="#{bean.endDate}">
     <p:ajax event="dateSelect" update="endDate"/>
</p:calendar>
<p:calendar id="endDate" value="#{bean.endDate}" mindate="#{bean.startDate}" disabled="#{empty bean.startDate}">
      <p:ajax event="dateSelect" update="startDate"/>
 </p:calendar>
于 2015-11-12T19:48:37.973 回答
3

像Base一样使用Answer BalusC,并为我将来使用......

这可以设置间隔(年、月、周)、参考比较初始或最终。

@FacesValidator("dateRangeValidator")
public class DateRangeValidator implements Validator {

   @Override
   public void validate(FacesContext facesContext, UIComponent component,
           Object value) throws ValidatorException {

       UIInput dateIniComponent = (UIInput) component.getAttributes().get("dateIniComponent");
       UIInput dateFinComponent = (UIInput) component.getAttributes().get("dateFinComponent");
       String range = ((String) component.getAttributes().get("range")).toLowerCase();
       String reference = ((String) component.getAttributes().get("reference")).toLowerCase();

       if (value == null) {
           return;
       } else if (value instanceof Date) {
           Date dateIni = null;
           Date dateFin = null;
           if ((dateIniComponent == null) && (dateFinComponent != null)) {
               if (!dateFinComponent.isValid()) {
                   return; //No hay datos contra quien comparar
               }
               dateFin = (Date) dateFinComponent.getValue();
               dateIni = (Date) value;
           }

           if ((dateFinComponent == null) && (dateIniComponent != null)) {
               if (!dateIniComponent.isValid()) {
                   return; //No hay datos contra quien comparar
               }
               dateIni = (Date) dateIniComponent.getValue();
               dateFin = (Date) value;
           }

           if ((dateIni != null) && (dateFin != null)) {
               Calendar cal = Calendar.getInstance();

               cal.setTime(dateIni);
               Integer yearIni = cal.get(Calendar.YEAR);
               Integer monthIni = cal.get(Calendar.MONTH);
               Long daysMonthIni = (long) YearMonth.of(yearIni, monthIni + 1).lengthOfMonth();
               Long daysYearIni = (long) cal.getActualMaximum(Calendar.DAY_OF_YEAR);

               cal.setTime(dateFin);
               Integer yearFin = cal.get(Calendar.YEAR);
               Integer monthFin = cal.get(Calendar.MONTH);
               Long daysMonthFin = (long) YearMonth.of(yearFin, monthFin + 1).lengthOfMonth();
               Long daysYearFin = (long) cal.getActualMaximum(Calendar.DAY_OF_YEAR);

               Long daysAllowed =
                       ("year".equals(range) ? ("ini".equals(reference)?daysYearIni:("fin".equals(reference)?daysYearFin:null)) :
                       ("month".equals(range) ? ("ini".equals(reference)?daysMonthIni:("fin".equals(reference)?daysMonthFin:null)) : 
                       ("week".equals(range) ? 7 : null)));

               Long daysBetweenDates = TimeUnit.DAYS.convert(dateFin.getTime() - dateIni.getTime(), TimeUnit.MILLISECONDS);

               if (daysAllowed == null) {
                   FacesMessage facesMessage
                           = new FacesMessage(
                                   FacesMessage.SEVERITY_ERROR,
                                   "Rango de fechas mal expresado en el facelet (vista) ",
                                   "Rango de fechas mal expresado en el facelet (vista) ");
                   throw new ValidatorException(facesMessage);
               }

               if (dateFin.before(dateIni)) {
                   FacesMessage facesMessage
                           = new FacesMessage(
                                   FacesMessage.SEVERITY_ERROR,
                                   "Fecha Final No es posterior a Fecha Inicial ",
                                   "La Fecha Final debe ser posterior a Fecha Inicial");
                   throw new ValidatorException(facesMessage);
               }

               if (daysBetweenDates > daysAllowed) {
                   FacesMessage facesMessage
                           = new FacesMessage(
                                   FacesMessage.SEVERITY_ERROR,
                                   "Se ha excedido los dias permitidos " + daysAllowed + " entre fechas seleccionadas, entre las fechas hay " + daysBetweenDates + " dias",
                                   "entre las fechas hay " + daysBetweenDates + " dias");
                   throw new ValidatorException(facesMessage);
               }
           }

       }
   }

}

现在在视图中

    <p:outputLabel value="Date Initial:" for="itHeadDateInitial" />
    <p:calendar id="itHeadDateInitial"
                navigator="true" 
                binding="#{bindingDateIniComponent}" 
                value="#{theBean.DateIni}"
                pattern="dd-MM-yyyy" mask="true" >
        <f:validator validatorId="dateRangeValidator" />
        <f:attribute name="dateFinComponent" value="#{bindingDateFinComponent}" />
        <f:attribute name="range" value="year" />
        <f:attribute name="reference" value="ini" />
    </p:calendar>


    <p:outputLabel value="Date Final:" for="itHeadDateFinal" />
    <p:calendar id="itHeadDateFinal"
                navigator="true" 
                binding="#{bindingDateFinComponent}" 
                value="#{theBean.DateFin}"
                pattern="dd-MM-yyyy" mask="true" >
        <f:validator validatorId="dateRangeValidator" />
        <f:attribute name="dateIniComponent" value="#{bindingDateIniComponent}" />
        <f:attribute name="range" value="year" />
        <f:attribute name="reference" value="ini" />
    </p:calendar>
于 2019-02-14T20:32:26.927 回答
2

由于 BalusC 解决方案仅在您在表单上验证一个日期范围时才有效,因此这是一项允许多个日期范围验证的改进:

  • 将另一个添加<f:attribute>到 endDate 日历组件,您可以在其中指定绑定属性名称到 startDate 组件:

    <f:attribute name="bindingAttributeName" value="startDateComponent" />
    
  • 然后在验证器中:

    String startDateBindingAttrName = (String) component.getAttributes().get("bindingAttributeName");
    UIInput startDateComponent = (UIInput) component.getAttributes().get(startDateBindingAttrName);
    
于 2016-02-25T16:53:21.617 回答