我想用自定义验证器创建选定的生日。 这是我的观点:
<h:selectOneMenu id="birthdate_day" value="#{userc.userb.b_day}">
<f:validator validatorId="dateExistValidator" />
<f:attribute name="day" value="#{dateExist.submittedValue}" />
<f:ajax event="blur" render="m_birthdate_day" />
<f:selectItem itemLabel="Dia" itemValue="" />
<f:selectItems value="#{userc.birthDateDays}" />
</h:selectOneMenu>
<h:selectOneMenu id="birthdate_month" value="#{userc.userb.b_month}" binding="#{dateExist}" >
<f:selectItem itemLabel="Mês" itemValue="" />
<f:selectItems value="#{userc.birthDateMonths}" var="month" itemValue="#{month.key}" itemLabel="#{month.value}" />
<f:ajax event="blur" execute="birthdate_day birthdate_month" render="m_birthdate_month" />
</h:selectOneMenu>
<h:selectOneMenu id="birthdate_year" value="#{userc.userb.b_year}">
<f:selectItem itemLabel="Ano" itemValue="" />
<f:selectItems value="#{userc.birthDateYears}" />
<f:ajax event="blur" render="m_birthdate_year" />
</h:selectOneMenu>
这是我的验证员:
@FacesValidator("dateExistValidator")
public class DateValidator implements Validator {
@Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
Integer day = (Integer) value;
Integer month = (Integer) component.getAttributes().get("month");
Integer year = (Integer) component.getAttributes().get("year");
if (day == null || month == null || year == null) {
return; // Just ignore and let required="true" do its job.
}
// do the verifications if the selected date exist
}
}
但由于某种原因,我的验证器中的month
和year
对象始终为空。
说实话,我不知道如何将selectItems
中的选定值与validator.
我该怎么做?或者我应该仅在用户提交表单时进行此验证吗?
答案 0 :(得分:1)
您发布的代码是否不完整?
任何方式都应该有效
<h:selectOneMenu id="birthdate_day" value="#{userc.userb.b_day}">
<f:validator validatorId="dateExistValidator" />
<f:attribute name="month" value="#{myMonth}" />
<f:attribute name="year" value="#{myYear}" />
<f:ajax event="blur" render="m_birthdate_day" />
<f:selectItem itemLabel="Dia" itemValue="" />
<f:selectItems value="#{userc.birthDateDays}" />
</h:selectOneMenu>
<h:selectOneMenu id="birthdate_month" value="#{userc.userb.b_month}" binding="#{myMonth}" >
<f:selectItem itemLabel="M?s" itemValue="" />
<f:selectItems value="#{userc.birthDateMonths}" var="month" itemValue="#{month.key}" itemLabel="#{month.value}" />
<f:ajax event="blur" execute="birthdate_day birthdate_month" render="m_birthdate_month" />
</h:selectOneMenu>
<h:selectOneMenu id="birthdate_year" value="#{userc.userb.b_year}" binding="#{myYear}">
<f:selectItem itemLabel="Ano" itemValue="" />
<f:selectItems value="#{userc.birthDateYears}" />
<f:ajax event="blur" render="m_birthdate_year" />
</h:selectOneMenu>
此外,要从属性中获取值,您应首先将它们转换为 UIElement ,然后提取它们的值,例如
UISelectOne month = (UISelectOne) component.getAttributes().get("myMonth");
month.getSubmittedValue()