我正在研究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>
我想验证第二个日期不在第一个日期之前的第一个和第二个日期
答案 0 :(得分: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);
}
}
}