2

我正在处理一个 JSF 2.0 表单,我有一个带有 2 个字段的 managedbean

import java.util.Date;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

@ManagedBean
@RequestScoped
public class StackOverflow {

    private Date firstDate;
    private Date secondDate;

    public void submit(){
       //validate here and show error on form
    }

}

和 xhtml 之类的:

<h:inputText value="#{stackOverflow.firstDate}">
    <f:convertDateTime pattern="d/M/yyyy" />
</h:inputText>
<h:inputText value="#{stackOverflow.secondDate}">
    <f:convertDateTime pattern="d/M/yyyy" />
</h:inputText>

<h:commandLink action="#{stackOverflow.submit}">
    <span>Submit</span>
</h:commandLink>

我想验证第二个日期不早于第一个日期的第一个和第二个日期

4

1 回答 1

4

这是其中一种方法:

<h:messages globalOnly="true"/>
<h:form>
    <h:inputText value="#{stackOverflow.firstDate}" binding="#{firstDate}">
        <f:convertDateTime pattern="d/M/yyyy" />
    </h:inputText>
    <h:inputText value="#{stackOverflow.secondDate}" validator="dateValidator">
        <f:attribute name="firstDate" value="#{firstDate}" />
        <f:convertDateTime pattern="d/M/yyyy" />
    </h:inputText>
    <h:commandButton value="Submit" action="#{stackOverflow.submit}"/>
</h:form>

@FacesValidator(value="dateValidator")
public class DateValidator implements Validator {

    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        UIInput sd = (UIInput)component.getAttributes().get("firstDate");
        Date firstDate = (Date)sd.getValue();
        Date secondDate = (Date)value;
        if(!firstDate.before(secondDate)){
            FacesMessage msg = new FacesMessage("Entered dates are invalid: first date must be before second date");
            throw new ValidatorException(msg);
        }
    }

}
于 2013-04-24T09:24:31.463 回答