You can do this validation by using a Custom Validator, by defining a java class implementing Validator
interface, which should performs the specific desired validation. Here's a small example that shows when the user types keywords (separated by "-") more than a predetermined max limit (e.g 5), a validation message pops up when passing to the next field :
View : index.xhtml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<title>Custom Validator Example</title>
</h:head>
<h:body>
<h:form>
<h:panelGrid columns="3">
Give strings separated by "-" :
<h:inputText id="input" size="30" required="true" requiredMessage="Field required" value="#{myBean.myExpression}">
<f:ajax event="blur" render="inputMessage" />
<f:validator binding="#{myValidator}" />
</h:inputText>
<h:message for="input" id="inputMessage" style="color:red" />
Enter your name:
<h:inputText id="input1" required="true" requiredMessage="missed name" value="#{myBean.name}" />
</h:panelGrid>
</h:form>
</h:body>
A simple managed-bean : MyBean.java
// imports
@ManagedBean
@RequestScoped
public class MyBean implements Serializable {
private String myExpression ;
private String name ;
// getters/setters
}
Custom Validator : MyValidator.java
// imports
@ManagedBean
@ViewScoped
public class MyValidator implements Validator {
@Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
int max_limit = 5; // for example
String expression = (String) value;
String[] result = expression.split("-");
int count=0;
for(int i=0;i<result.length;i++){
if (result[i].equals("")) continue; // Empty keywords (e.g successive "-" caracters) are ignored. Else, just omit this line
count++;
}
if (count > max_limit) {
FacesMessage facesmsg = new FacesMessage(FacesMessage.SEVERITY_ERROR,"Exeeded allowed limit !",null);
throw new ValidatorException(facesmsg);
}
}
}