更新时间:2023-11-26 21:35:16
您需要的是Validator
.它应该看起来像这样:
What you need is a Validator
. It should look like this:
@ManagedBean
@RequestScoped
public class DiscountCodeValidator implements Validator {
@EJB
private MrBean mrBean;
@Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
String discountCode = (String) value;
if (!mrBean.checkDiscountCodeExistence(discountCode)) {
throw new ValidatorException(new FacesMessage("This code is not valid!"));
}
}
}
在您的.xhtml文件中,您可以按以下方式声明此验证器:
In your .xhtml file, you can declare this validator as following:
<h:inputText id="discountCode" value="#{someBean.discountCode}"
validator="#{discountCodeValidator}"
required="true" requiredMessage="Discount code is required.">
<f:ajax event="blur" render="discountMsg" />
</h:inputText>
<h:message for="discountCode" id="discountMsg"/>
要注意的一件事是,我假设您将注入一个EJB以使用checkDiscountCodeExistence()
函数检查折扣代码的存在.因此,我将上述验证器注释为@ManagedBean
.如果不需要注入任何EJB,则可以使用@FacesValidator
注释验证器.
One thing to note is I assume that you would inject an EJB to check the existence of the discount code with the checkDiscountCodeExistence()
function. Hence, I annotated the above Validator as a @ManagedBean
. If you don't need to inject any EJBs, you can annotate the Validator with @FacesValidator
.