How to validate if a foreign key entry exists?

孤人 提交于 2019-12-01 20:26:53

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!"));
        }
    }
}

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"/>

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!