Validate input as required only if certain command button is pressed

后端 未结 2 1493
死守一世寂寞
死守一世寂寞 2021-02-06 06:51

I have specific use case for JSF validation. For example I have an inputText field:



        
相关标签:
2条回答
  • 2021-02-06 07:19

    Let the input's required attribute check if the save button is pressed or not (which can be identified by the presence of its client ID in the request parameter map).

    <h:form>
        <p:inputText ... required="#{not empty param[save.clientId] and myBean.required}" />
    
        <p:commandButton binding="#{save}" ... />
    </h:form>
    

    (note: do not bind it to a bean property! the code is as-is)

    This way it would only evaluate true when the save button is actually pressed.

    Or, if you have problems with binding and/or don't have a problem hardcoding the button's client ID:

    <h:form id="formId">
        <p:inputText ... required="#{not empty param['formId:buttonId'] and myBean.required}" />
    
        <p:commandButton id="buttonId" ... />
    </h:form>
    
    0 讨论(0)
  • 2021-02-06 07:28

    Just remove the required attribute as you accept the input if the input is empty. Then write a custom validator which accepts only empty input or numerical input.

    <p:inputText id="input" value="#{myBean.value}" maxlength="20" disabled="#{myBean.disabled}" validator="customerNumericInputValidator">   <p:ajax event="blur" process="@this" update="name" listener="#{myBean.listener}"/> </p:inputText>
    

    public class customerNumericInputValidator implements Validator {

    @Override
    public void validate(FacesContext facesContext, UIComponent uIComponent,
            Object object) throws ValidatorException {
    
        String number = (String) object;
        number = Strings.nullToEmpty(number).trim();
    
        //if the request is a full request then number can not be empty
        if(!FacesContext.getCurrentInstance().isPostback() && Strings.isNullOrEmpty(number))
        {
             FacesMessage message = new FacesMessage();
             message.setSummary(Messages.getMessage("error empty value"));
             message.setSeverity(FacesMessage.SEVERITY_ERROR);
             throw new ValidatorException(message);
        } 
    
        if(!Strings.isNullOrEmpty(number))
        { 
            if(!isNumber(number))
            {
               FacesMessage message = new FacesMessage();
               message.setSummary(Messages.getMessage("error not numerical value"));
               message.setSeverity(FacesMessage.SEVERITY_ERROR);
               throw new ValidatorException(message);
            }
        }
    }
    

    }

    0 讨论(0)
提交回复
热议问题