Search code examples
jsfjsf-2primefaces

Validate a action in form when click commandbutton


I want to know if is possible to validate dates before to execute the action to open a new tab in the navigator.

I have a form that have two fields to enter the date values, so when user press the commandButton it will open the other form with the values filtered in other tab.

So the problem is, if didn´t enter a correct date it will open the new tab.

<p:column>
  <p:calendar locale="pt_BR" pattern="dd/MM/yyyy" value="#{relatorioDesempenhoAnalistaListBean.filter.dataInicial}" required="true" label="#{lbl['LABEL.RELATORIOANALISTA.ENTREDATAS']}"/>
</p:column>

<p:column>
  <p:calendar locale="pt_BR" pattern="dd/MM/yyyy" value="#{relatorioDesempenhoAnalistaListBean.filter.dataFinal}" required="true"  label="#{lbl['LABEL.RELATORIOANALISTA.ENTREDATAS']}"/>
</p:column>


<p:column colspan="3" styleClass="columnRight">
  <p:commandButton value="#{lbl['BOTAO.GERARRELATORIO']}" action="form" ajax="false" onclick="target='_blank'"/>
</p:column>

My code is above.


Solution

  • Add a custom date validator similar to this

    @FacesValidator(value="check_If_date_is_valid")
    public class CheckDate implements Validator{
    
        @Override
        public void validate(FacesContext facescontext, UIComponent uicomponent,Object obj) throws ValidatorException {
             Date _userInput=(Date)obj;
                if(isThisDateValid(_userInput.toString(),"dd/MM/yyyy")){
                   //do nothing 
                }else{
                      throw new ValidatorException(new FacesMessage("Date not valid"));
                }
         }
    
        public boolean isThisDateValid(String dateToValidate, String dateFromat){
    
        if(dateToValidate == null){
            return false;
        }
    
        SimpleDateFormat sdf = new SimpleDateFormat(dateFromat);
        sdf.setLenient(false);
    
        try {
    
            //if not valid, it will throw ParseException
            Date date = sdf.parse(dateToValidate);
            System.out.println(date);
    
        } catch (ParseException e) {
    
            e.printStackTrace();
            return false;
        }
    
        return true;
    }
    
                
    
    }
    

    And on the page

    <p:commandButton>
      <f:validator validatorId="check_If_date_is_valid" />
      <f:ajax execute="@form" render="@form"/>
    </p:commandButton>
    

    And add <p:message/>on the page to display the error message

    If their is a validation error your action method of managedBean will not be called. and heance tab will not open.