我有一种情况,我需要覆盖或扩展默认的必需验证器,以便我可以在缺少所需的值时在服务器端执行多个操作。
我只是通过扩展标准的RequiredValidator来尝试它,但是当提交的值不为null时,验证器才会被触发:
import static com.util.ResourceBundleHelper.getMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.RequiredValidator;
import javax.faces.validator.ValidatorException;
import org.omnifaces.util.Ajax;
@FacesValidator("com.util.validator.AjaxRequiredValidator")
public class AjaxRequiredValidator extends RequiredValidator {
@Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
//need to perform additional logic here, depending on the actual component parameter
if (value == null || value.toString().isEmpty()){
String javascriptMethod = "MODULE.error(" + component.getId() + ")";
Ajax.oncomplete(javascriptMethod);
throw new ValidatorException(getMessage("error"));
}
}
}
XHTML:
<h:inputText value="#{bean.requiredValue}">
<f:validator validatorId="com.util.validator.AjaxRequiredValidator"/>
</h:inputText>
我读到了context-param:
<context-param>
<param-name>javax.faces.VALIDATE_EMPTY_FIELDS</param-name>
<param-value>true</param-value>
</context-param>
但我不想全局设置此行为,仅针对特定组件。这可能吗?
为什么/如何在我使用时触发默认验证器:
<h:inputText value="#{bean.requiredValue}" required="true"/>
答案 0 :(得分:0)
因为它没有受到伤害,所以我去了web.xml中的context-param解决方案:
<context-param>
<param-name>javax.faces.VALIDATE_EMPTY_FIELDS</param-name>
<param-value>true</param-value>
</context-param>
<h:inputText value="#{bean.requiredValue}" validator="#{bean.validateRequired}"/>
public interface RequiredValidation {
default public void validateRequired(FacesContext context, UIComponent component, Object value) {
if (value == null || value.toString().isEmpty()){
String javascriptMethod = "MAINMODULE.error(" + component.getId() + ")";
throw new AjaxValidatorException(javascriptMethod,"fieldRequired");
}
}
}
@ManagedBean
@ViewScoped
public class Bean implements RequiredValidation {
private String requiredValue;
//...
}