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?
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
.
来源:https://stackoverflow.com/questions/8629550/how-to-validate-if-a-foreign-key-entry-exists