Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate if a foreign key entry exists?

I have foreign key inside my Customer table.

@JoinColumn(name = "DISCOUNT_CODE", referencedColumnName = "DISCOUNT_CODE")
@ManyToOne(optional = false)
private DiscountCode discountCode;

I have a form that contains all fields of this table (including the foreign key discountCode and its description from the other table).

I want to be able to show a message that this foreign key does not exist in case that the user entered an input that does not exist in the foreign key table. When I onblur this field, then I'm retriving its description from the table. How can I show the error message of invalid field when the user onblurs it and it does not exist in the table?

like image 785
user590586 Avatar asked Nov 15 '25 11:11

user590586


1 Answers

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.

like image 151
Mr.J4mes Avatar answered Nov 17 '25 05:11

Mr.J4mes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!