Validate input as required only if certain command button is pressed

后端 未结 2 1492
死守一世寂寞
死守一世寂寞 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: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.

        
    

    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);
            }
        }
    }
    

    }

提交回复
热议问题