JSF + Ajax + Custom Validator + FacesMessage example!

Here we go.

StudentNameValidator.java
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;
 
/**
 * User: Koray Tugay (koray@tugay.biz)
 * Date: 7/3/2016
 * Time: 6:08 PM
 */
 
@FacesValidator("biz.tugay.StudentNameValidator")
public class StudentNameValidator implements Validator {
    public void validate(FacesContext context, UIComponent component, Object value) 
            throws ValidatorException {
        final String studentName = (String) value;
        if(studentName.contains("_")) {
            final FacesMessage validationMessage = 
                    new FacesMessage("", "Student name can not have underscore!");
            throw new ValidatorException(validationMessage);
        }
    }
}

view:
<!DOCTYPE html>
<html xmlns:h="http://xmlns.jcp.org/jsf/html"
      xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head>
    <title>Echo Name</title>
</h:head>
<h:body>
    <h:form>
        <h:inputText id="studentname" value="#{student.firstname}">
            <f:validator validatorId="biz.tugay.StudentNameValidator"/>
            <f:ajax event="keyup"
                    execute="studentname"
                    render="studentnamemessage"/>
        </h:inputText>
        <br/>
        <br/>
        <h:message id="studentnamemessage"
                   for="studentname"
                   style="color: red; font-weight: bold"/>
    </h:form>
</h:body>
</html>

In action: