用于日期转换器的 Primefaces 输入掩码

Primefaces input mask for date converter

嗯。我在所有地方都找到了,但我仍然没有解决方案。我需要使用 Primefaces 做一个输入掩码并将值绑定到我的 bean 中的日期对象。

问题是:我使用带有所有验证、转换和格式的转换器以及我自己的代码。我的回答是:是其他性能更好的解决方案。但愿如此。请帮忙。

P/D: 我不需要使用 pickdate。我需要输入掩码来执行此操作

嗯,这是我的解决方案

<h:form>
      <p:inputMask mask="99-99-9999" value="#{mask.date}" converterMessage="Invalid Date!" converter="dateconverter" />
      <h:commandButton actionListener="#{mask.submit()}" value="Submit" />
</h:form>

和转换器

@Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
    System.out.println(value);
    if (value != null) {
        try {
            if (validateDate(value)) {
                return convertDate(value).toDate();
            }
            else{
                throw new ConverterException("Invalid date!");
            }
        } catch (Exception e) {
            throw new ConverterException("Invalid date!");
        }
    }
    throw new ConverterException("Null String!");
}
@Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
    System.out.println(value);
    if (value != null) {
        try {
            Date now = (Date)value;
            DateTime d = new DateTime(now);
            return d.getDayOfMonth() + "-" + d.monthOfYear() + "-" + d.getYear();
        } catch (Exception e) {
            throw new ConverterException("Convertion failure!");
        }
    }
    throw new ConverterException("Null object!");
}
private boolean validateDate(String param) throws ParseException{
    //Param is a date format from input mask
    String[] values = param.split("-");
    int day = Integer.valueOf(values[0]);
    int month = Integer.valueOf(values[1]);
    int year = Integer.valueOf(values[2]);
    DateTime converted = convertDate(param);
    if (converted.getDayOfMonth() != day || converted.getMonthOfYear() != month || converted.getYear() != year) {
        return false;
    }
    else{
        return true;
    }
}
private DateTime convertDate(String param) throws ParseException{
   SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
   Date convertedCurrentDate = sdf.parse(param);
   return new DateTime(convertedCurrentDate);
}

托管 Bean

@ManagedBean(name="mask")
public class MaskBean {

private Date date;

public Date getDate() {
    return date;
}

public void setDate(Date date) {
    this.date = date;
}

public void submit(){
    RequestContext context = RequestContext.getCurrentInstance();
    context.execute("alert('date submited: value recibed " + date.toString() + "')");
}

}

对我有用。

我用这个:

<div style="margin-bottom:1em;font-size: 1.2em;"> 
    <p:inputMask id="dob" mask="99/99/9999" value="#{viewMB.request.dateOfBirth}" style="width:8em;" >
        <f:convertDateTime pattern="MM/dd/yyyy" />
    </p:inputMask>
    <p:watermark  value="MM/DD/YYYY" for="dob" />
</div>

如果您愿意,您仍然可以添加自定义验证器。