我想实现自定义验证器,我可以在其中使用 CDI 和数据源。我测试了这段代码:
<h:panelGroup>Session ID</h:panelGroup>
<h:panelGroup>
<h:inputText id="sessionid" value="#{DatabaseController.formMap['sessionid']}" >
<f:validateLength minimum="0" maximum="15"/>
<f:validator validatorId="ValidatorController" >
</f:validator>
<f:ajax event="blur" render="sessionidMessage" />
</h:inputText>
<h:message id="sessionidMessage" for="sessionid" />
</h:panelGroup>
这是验证器:
@FacesValidator("ValidatorController")
public class FormValidator implements Validator {
public FormValidator() {
}
@Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
if (value.equals("test")) {
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
" Session ID is already in use, please choose another.", null));
}
}
}
这段代码工作正常。我还尝试实现此代码,以便在验证器中使用 CDI:
<h:panelGroup>Session ID</h:panelGroup>
<h:panelGroup>
<h:inputText id="sessionid" value="#{DatabaseController.formMap['sessionid']}" >
<f:validateLength minimum="0" maximum="15"/>
<f:validator binding="#{ValidatorController}" >
<f:attribute name="type" value="sessionid" />
</f:validator>
<f:ajax event="blur" render="sessionidMessage" />
</h:inputText>
<h:message id="sessionidMessage" for="sessionid" />
</h:panelGroup>
这是验证器:
@Named("ValidatorController")
public class FormValidator implements Validator {
public FormValidator() {
}
@Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
if (value.equals("test")) {
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
" Session ID is already in use, please choose another.", null));
}
}
}
由于某种原因,第二个示例不起作用。