How to Write a Validator for a Nuxeo Studio Widget FieldHow to Write a Validator for a Nuxeo Studio Widget Field

Here’s a question from zod who asks how to write a custom validator method.

The first thing to know before we proceed further is that a Nuxeo Studio widget is rendered using JSF. So the question is how to write a JSF validator. And since we are using the SEAM Framework to leverage JSF, the complete question is how to write a JSF/SEAM validator.

Let’s take a simple example. I created a String field called email. I want to make sure that this field is filled correctly. For the purpose of this blog I will only check if the email address has an ‘@‘ character.

Let’s write a Java class that has a validation method and is a SEAM component:

package org.nuxeo.sample;

import java.io.Serializable;
import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;

@Name("businessValidatorSample")
@Scope(ScopeType.STATELESS)
public class BusinessValidatorSampleBean implements Serializable {

    private static final long serialVersionUID = 1L;

    private static final Log log = LogFactory
            .getLog(BusinessValidatorSampleBean.class);

    @In(create = true)
    protected Map<String, String> messages;

    public void validateEmail(FacesContext context, UIComponent component,
            Object value) {
        String email = (String) value;
        if (email.contains("@")) {
            // ok
            return;
        }
        String msg = messages.get("error.notifManager.noUserSelected");
        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR,
                msg, msg);
        throw new ValidatorException(message);
    }

}

As you can see, the SEAM component is named businessValidatorSample and the validation method, validateEmail. This means that in Nuxeo Studio, during the widget configuration, we’ll have to write #{businessValidatorSample.validateEmail} in the Validator field.

Validator Sample

As for the code, it’s a really simple. Just cast the parameter value as a String and verify if it contains the ‘@‘ character. Know that any method you use as a validator must have the following signature: public void methodName(FacesContext context, UIComponent component, Object value)

And the method must throw a new ValidatorException if the value is not as intended.

I might do a marketplace package with a bunch of pre-configured validators. Let me know if you would find it useful and if so what validators you would like to find in it.