I have an input text that have required=true
attribute, like below
<h:panelGrid columns=2>
<h:panelGroup id="ccm">
<p:inputText id="txtCCMNumber" value="#{setupView.selectedCCM}"
required="true" requiredMessage="Required">
<p:ajax event="blur" listener="#{setupView.handleLooseFocusCCMTextbox()}"
update=":setupForm:ccm :setupForm:ccmMsg"/>
</p:inputText>
<h:outputText value="Duplicated" id="ccmExisted"
styleClass="ui-message-error ui-widget ui-corner-all"
rendered="#{setupView.ccmNameExisted}"/>
<h:graphicImage id="ccmNotExist" url="resources/images/check-icon.png"
rendered="#{setupView.ccmNameUnique}"
width="18"/>
</h:panelGroup>
<p:message for="txtCCMNumber" id="ccmMsg" display="text"/>
</h:panelGrid>
So my requirement is, if the value is empty, then it will display Required
, since required=true
, it should fail at Process Validation phase. If the value is unique, then display a check
image, if duplicated, then display Duplicated
text. The problem that I run into is, after I type something and tab away (let say I type something unique), it displays the check
image, I then erase the text, and tab away again, now the Required
text appear, but so is the check
image. My theory is that, at the Process validation
phase, it fail due to the value is empty, so at the update component phase, it does not invoke that method handleLooseFocusCCMTextbox()
that will set the boolean ccmNameUnique
to false
. Is there a way to fix this?
NOTE: handleLooseFocusCCMTextbox() just turn the boolean value on and off to display the check
image or Duplicated
text.
Answered. Create Validator class, take out required=true
public void validate(FacesContext fc, UIComponent uic, Object value)
throws ValidatorException {
FacesContext context = FacesContext.getCurrentInstance();
SetupView setupView = (SetupView) context.getApplication().
evaluateExpressionGet(context, "#{setupView}", SetupView.class);
if (value == null || value.toString().isEmpty()) {
setupView.setCcmNameUnique(false);
FacesMessage message = new FacesMessage();
message.setSeverity(FacesMessage.SEVERITY_ERROR);
message.setSummary("Error");
message.setDetail("Required");
//This will end up in <p:message>
throw new ValidatorException(message);
}
String rootPath = setupView.getRootPath();
File rootFolder = new File(rootPath);
if (rootFolder.exists() && rootFolder.canRead()) {
List<String> folderNames = Arrays.asList(new File(rootPath).list());
if (folderNames.contains(value.toString())) {
setupView.setCcmNameUnique(false);
FacesMessage message = new FacesMessage();
message.setSeverity(FacesMessage.SEVERITY_ERROR);
message.setSummary("Error");
message.setDetail("Duplicate");
//This will end up in <p:message>
throw new ValidatorException(message);
} else {
setupView.setCcmNameUnique(true);
}
} else {
logger.log(Level.SEVERE, "Please check the root folder path as "
+ "we cannot seems to see it. The path is {0}", rootPath);
}
}