Add global message when field validation fails

后端 未结 1 1619
感动是毒
感动是毒 2021-01-15 06:12

Usually the PrimeFaces tag for messages shows the global as well as the field specific messages. What I want to do is to just show the global messages (globalOnly=\"tr

相关标签:
1条回答
  • 2021-01-15 06:57

    I use a phase listener to do so. This is roughly my implementation (using OmniFaces):

    public class ValidationFailedListener implements PhaseListener {
    
      @Override
      public void afterPhase(PhaseEvent event) {
        // NOOP
      }
    
      @Override
      public void beforePhase(PhaseEvent event) {
        if (Faces.isValidationFailed()) {
          Messages.addGlobalError("Your validation failed message");
        }
      }
    
      @Override
      public PhaseId getPhaseId() {
        return PhaseId.RENDER_RESPONSE;
      }
    
    }
    

    You should register it in your faces-config.xml:

    <lifecycle>
      <phase-listener>your.ValidationFailedListener</phase-listener>
    </lifecycle>
    

    My actual implementation uses a message bundle to display a localized message.


    If you cannot use OmniFaces, here is the relevant code using vanilla JSF:

    if (FacesContext.getCurrentInstance().isValidationFailed()) {
      FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                              "Your validation failed message",
                                              null);
      FacesContext.getCurrentInstance().addMessage(null, message);
    }
    
    0 讨论(0)
提交回复
热议问题