メッセージが 2 回表示される場合は、両方のコンポーネントで同じバリデーターを起動しているか、バリデーターが 1 回起動されているが暗黙的にメッセージを他のコンポーネントに追加していることを意味します。
両方のコンポーネントを無効としてマークし (ハイライト表示するため)、メッセージを 1 つだけにしたいということは理解しています。その場合、バリデーターが一度起動され、他のコンポーネントが空/null メッセージを取得していることを確認する必要があります。
コンポーネント全体をその値ではなく属性として取得するようにバリデーターを変更するだけで済み (注: その間、それに応じて古い記事を編集しました。これには別の利点があります)、フェーズ リスナーを変更して empty/ を削除する必要があります。ヌル メッセージ。
例:
<h:outputLabel for="password" value="Password" />
<h:inputSecret id="password" value="#{bean.password}" required="true">
<f:validator validatorId="passwordValidator" />
<f:attribute name="confirm" value="#{confirm}" />
</h:inputSecret>
<h:message for="password" styleClass="error" />
<h:outputLabel for="confirm" value="Confirm password" />
<h:inputSecret id="confirm" binding="#{confirm}" required="true" />
<h:message for="confirm" styleClass="error" />
そしてvalidate()
方法で:
String password = (String) value;
UIInput confirmComponent = (UIInput) component.getAttributes().get("confirm");
String confirm = confirmComponent.getSubmittedValue();
if (password == null || password.isEmpty() || confirm == null || confirm.isEmpty()) {
return; // Let required="true" do its job.
}
if (!password.equals(confirm)) {
confirmComponent.setValid(false);
context.addMessage(confirmComponent.getClientId(context), new FacesMessage(null));
throw new ValidatorException(new FacesMessage("Passwords are not equal."));
}
そしてフェーズリスナーで:
Iterator<String> clientIdsWithMessages = facesContext.getClientIdsWithMessages();
while (clientIdsWithMessages.hasNext()) {
String clientIdWithMessages = clientIdsWithMessages.next();
if (focus == null) {
focus = clientIdWithMessages;
}
highlight.append(clientIdWithMessages);
if (clientIdsWithMessages.hasNext()) {
highlight.append(",");
}
Iterator<FacesMessage> messages = facesContext.getMessages(clientIdWithMessages);
while (messages.hasNext()) {
if (messages.next().getSummary() == null) {
messages.remove(); // Remove empty messages.
}
}
}
関連している:
具体的な問題とは関係ありませんが、 JSF2には、無効なフィールドを強調表示する別の方法があります。#{component}
ELの新しい暗黙の変数でそれを行うことができます:
<h:inputText styleClass="#{component.valid ? '' : 'error'}" />