Assume that you have a text box in your web page. You need to force the user to enter a text starts with letter 'A'. Following example shows how to do it.
This is the JSF page.
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head></h:head>
<body>
<h:form>
<h:inputText id="txt1">
<f:validator validatorId="myValidator"/>
</h:inputText>
<h:message for="txt1" style="color:red" />
<br/>
<h:commandButton value="Click Me" />
</h:form>
</body>
</html>
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head></h:head>
<body>
<h:form>
<h:inputText id="txt1">
<f:validator validatorId="myValidator"/>
</h:inputText>
<h:message for="txt1" style="color:red" />
<br/>
<h:commandButton value="Click Me" />
</h:form>
</body>
</html>
Note that in above page we have added a <h:message/> to display the error message. This is not a must.
Following is out validator class. Validator class should implement the javax.faces.validator.Validator and its validate() method. We should write our logic so that this method throws javax.faces.validator.ValidatorException if the validation failed.
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
@FacesValidator("myValidator")
public class MyValidator implements Validator {
@Override
public void validate(FacesContext ctx, UIComponent comp, Object val)
throws ValidatorException {
if(!val.toString().startsWith("A")) {
FacesMessage msg = new FacesMessage("Please enter a value starts with 'A'");
throw new ValidatorException(msg);
}
}
}
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
@FacesValidator("myValidator")
public class MyValidator implements Validator {
@Override
public void validate(FacesContext ctx, UIComponent comp, Object val)
throws ValidatorException {
if(!val.toString().startsWith("A")) {
FacesMessage msg = new FacesMessage("Please enter a value starts with 'A'");
throw new ValidatorException(msg);
}
}
}
Now run the project and go to the page. Enter a text which doesn't start with 'A' and click the button. A message should be displayed as below.