Migore
Migore

Reputation: 1497

How to validate uniqueness in JSF and get a message to the user?

I need to check the uniqueness of a field in my application.

I tried to use Hibernate @Unique constraint but it shows a stacktrace, but no error message in the user form.

My next solution would be to write a custom validator, but I think there is a better solution.

Is there a easier way to do this in JSF?

(JSF 2.1 + RichFaces)

Upvotes: 0

Views: 3962

Answers (3)

user3236565
user3236565

Reputation: 21

I hacked away a quick'n dirty working solution for JSF 2.1 unique key validation for my base entities:

usage:

<p:inputText id="name" value="#{employeesController.currentEmployee.name}">
    <f:validator validatorId="uniqueColumnValidator" />
    <f:attribute name="currentEntity" value="#{employeesController.currentEmployee}" />
    <f:attribute name="uniqueColumn" value="name" />
</p:inputText>

validator:

@RequestScoped
@FacesValidator("uniqueColumnValidator")
public class UniqueColumnValidator implements Validator, Serializable {

    @PersistenceContext
    protected EntityManager em;

    /**
     * generic unique constraint validator for AbstractBaseEntity entities<br />
     * requires the following additional attributes on the form element ("<f:attribute>"):<br />
     * - "currentEntity" the entity instance (used for getting the class and guid)<br />
     * - "uniqueColumn" the column where the new value will be checked for uniqueness
     */
    @Override
    public void validate(final FacesContext context, final UIComponent comp, final Object newValue) throws ValidatorException {

    AbstractBaseEntity currentEntity = (AbstractBaseEntity) comp.getAttributes().get("currentEntity");
    String uniqueColumn = (String) comp.getAttributes().get("uniqueColumn");

    boolean isValid = false;
    try {
        em.createQuery(
                "FROM " + currentEntity.getClass().getSimpleName()
                + " WHERE " + uniqueColumn + " = :value"
                + " AND guid <> :guid", currentEntity.getClass())
                .setParameter("value", value)
                .setParameter("guid", currentEntity.getGuid())
                .getSingleResult();
    } catch (NoResultException ex) {
        isValid = true; // good! no result means unique validation was OK!
    }

    if (!isValid) {
        FacesMessage msg = Messages.createError("must be unique", uniqueColumn);
        context.addMessage(comp.getClientId(context), msg);
        throw new ValidatorException(msg);
    }
    }
}

Upvotes: 2

dShringi
dShringi

Reputation: 1497

You can use <f:ajax /> or onblur event on the textfield and validate in your backing bean for all the model values which aren't null.

<h:message id="errorMessageTag" for="fieldId"/>
<h:inputText id="fieldId" value="#{beanName.modelName.variableName}">
    <f:ajax event="blur" listener="#{beanName.property}" render="errorMessageTag" />
</h:inputText>

Upvotes: 0

bhdrkn
bhdrkn

Reputation: 6702

You can manually validate your beans an ajax request. An example of manual validation is given down below.

ClassValidator<TestClass> classValidator = new ClassValidator<TestClass>(
              TestClass.class );

InvalidValue[] invalidValues = classValidator
        .getInvalidValues(testObject);

for (InvalidValue invalidValue : invalidValues) {
       System. out .println( "Property Name: "
               + invalidValue.getPropertyName() + " Message: "
               + invalidValue.getMessage());
}

You can catch ajax request using <a4j:support /> tag

Upvotes: 0

Related Questions