f:validator

The f:validator Facelet tag exposes the functionality of a Validator inside Facelet views. f:validator tags facilitate validation of complex data structures.

General Usage

Validators must be annotated with @FacesValidator (or declared as a validator in a faces-config.xml file) and implement Validator in order to be accessible via the f:validator tag.



                   

Source Code

  1. <ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:f="http://xmlns.jcp.org/jsf/core"
  2. xmlns:ui="http://xmlns.jcp.org/jsf/facelets" xmlns:h="http://xmlns.jcp.org/jsf/html">
  3.  
  4. <h:form>
  5. <label class="control-label">#{i18n['please-enter-your-email']}</label>
  6. <h:inputText id="email" value="#{inputTextModelBean.text}" label="#{i18n['validate-email-label']}">
  7. <f:validator validatorId="com.liferay.faces.showcase.validator.EmailValidator" />
  8. </h:inputText>
  9. <br />
  10. <h:message for="email" />
  11. <hr />
  12. <h:commandButton value="#{i18n['submit']}">
  13. <f:ajax execute="@form" render="@form" />
  14. </h:commandButton>
  15. <h:outputText value="#{inputTextModelBean.text}" />
  16. </h:form>
  17.  
  18. </ui:composition>
  1. @ManagedBean
  2. @RequestScoped
  3. public class InputTextModelBean {
  4.  
  5. private Date date = new GregorianCalendar().getTime();
  6. private String text;
  7.  
  8. public Date getDate() {
  9. return date;
  10. }
  11.  
  12. public String getText() {
  13. return text;
  14. }
  15.  
  16. public void setDate(Date date) {
  17. this.date = date;
  18. }
  19.  
  20. public void setText(String text) {
  21. this.text = text;
  22. }
  23. }
  1. @FacesValidator("com.liferay.faces.showcase.validator.EmailValidator")
  2. public class EmailValidator implements Validator {
  3.  
  4. private static final String EMAIL_REGEX = ".+[@].+[.].+";
  5.  
  6. @Override
  7. public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
  8.  
  9. String message = "";
  10.  
  11. try {
  12. Pattern pattern = Pattern.compile(EMAIL_REGEX);
  13. Matcher matcher = pattern.matcher((String) value);
  14.  
  15. if (!matcher.matches()) {
  16. message = ValidatorHelper.getMessage(context, "email-is-not-valid");
  17.  
  18. FacesMessage facesMessage = new FacesMessage(FacesMessage.SEVERITY_WARN, message, message);
  19. throw new ValidatorException(facesMessage);
  20. }
  21. }
  22. catch (PatternSyntaxException pse) {
  23. message = ValidatorHelper.getMessage(context, "unexpected-validation-error-ocurred");
  24.  
  25. FacesMessage facesMessage = new FacesMessage(FacesMessage.SEVERITY_FATAL, message, message);
  26. throw new ValidatorException(facesMessage);
  27. }
  28. }
  29. }
Liferay Faces Bridge Implementation 5.0.0 + Showcase Common 3.1.1 + Liferay Faces Util 3.4.1 + Mojarra 2.2.20