Skip to content

Instantly share code, notes, and snippets.

@zonia3000
Last active March 25, 2016 08:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zonia3000/d9bf8c41695aa8818b5a to your computer and use it in GitHub Desktop.
Save zonia3000/d9bf8c41695aa8818b5a to your computer and use it in GitHub Desktop.
JSF: h:inputText Validator vs custom Converter

JSF: h:inputText Validator vs custom Converter

Validator method

xhtml:

<h:inputText value="#{myBean.inputValue}" validator="#{myBean.validateInput}" />

Java:

public void validateInput(FacesContext context, UIComponent inputComponent, Object value) {
  String textValue = (String) value;
    
  // validate value ...
    
  if(!valid) {
    throw new ValidatorException(new FacesMessage("Text not valid"));  
  }
}

Custom converter

xhtml:

<h:inputText value="#{myBean.inputValue}">
  <f:converter converterId="com.example.MyConverter"/>
</h:inputText>

Java:

@FacesConverter("com.example.MyConverter")
public class TimeConverter implements Converter {
  
  @Override
  public Object getAsObject(FacesContext context, UIComponent component, String value) {
    if(value == null) {
      return null;
    }
  
    // validate value ...
  
    if (valid) {
      return value;
    }
  
    FacesMessage msg = new FacesMessage("Text not valid");
    msg.setSeverity(FacesMessage.SEVERITY_ERROR);
    throw new ConverterException(msg);
  }
  
  @Override
  public String getAsString(FacesContext context, UIComponent component, Object value) {
    return (String) value;
  } 
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment