簡単な背景 : 私は自分の Web サイトに primefaces カスタム コンポーネントを使用してキャプチャを配置しました。担当者は、使い方が難しすぎて気に入らず、クライアントから不満が寄せられています。少しのスパムを避けるために、単純なコンポーネント (つまり、4 + 9 = とユーザーが答えを入力する) を作成することにしました。簡単なテキストを使用するだけで、質問を画像で表示する必要はありません。これにより、カスタム コンポーネントと複合コンポーネントを調べるようになりました (この記事とこの記事から)。
さて、問題はその場しのぎの基本的な「キャプチャ スタイルの検証」についてではありません。これは、複合コンポーネントとバッキング Bean の組み合わせに関するものです。
私がすることは、このスタイルでバッキング Bean を作成することです。
<cc:interface>
<cc:attribute name="label" />
<!-- edited -->
<cc:attribute name="required" />
<cc:attribute name="ident" />
</cc:interface>
<cc:implementation>
<h:panelGrid columns="3">
<h:outputText value="#{captcha.text}"/>
<h:inputText id="#{cc.attrs.ident}" value="#{captcha.entered}" validator="#{captcha.validate}" required="#{cc.attrs.required eq 'true'}" label="#{cc.attrs.label}" />
<h:message for="captchaAnswer" />
</h:panelGrid>
<h:inputHidden value="#{captcha.value}" />
</cc:implementation>
そして、このコンポーネントを次のように使用したいと思います。
<h:form>
...
<tr>
<td>
<my:captcha label="Captcha" ident="captcha" required="true"/> <!-- added after suggested comment -->
<br/>
<h:message for="captcha" class="error"/>
</td>
</tr>
<tr>
<td colspan="3" class="center">
<h:commandButton class="button" value="#{msg['contact.label.send']}" action="#{contact.send}" >
</h:commandButton>
</td>
</tr>
...
</h:form>
{#captcha.entered}
送信時に自分の値が必要な値であることを確認し、そうでない場合はフォームに検証メッセージを返し、送信されないようにするにはどうすればよいですか?
captcha
バッキング Bean は単純で、値 : text
、answer
、および、entered
および if をチェックする単純な関数を持ちますanswer == entered
。
編集: (試行 #1) カスタムバリデーターは次のようになります
public void validate(FacesContext context, UIComponent toValidate, Object value) {
System.out.println("validating");
String input = (String) value;
//check to see if input is an integer
//if not we know right away that the value is not good
if(StringUtils.isNumeric(input)) {
//if the input is numeric, convert to an integer
int intValue = new Integer(input).intValue();
if (intValue != answer) {
((UIInput) toValidate).setValid(false);
FacesMessage message = new FacesMessage("Not a match!!");
context.addMessage(toValidate.getClientId(context), message);
}
}
}
この場合、バリデータは呼び出されず、エラー メッセージも表示されません。
編集#2
ちょっとした作業とコメントからのヒントの後、私はこれを機能させました。動作させるには、の代わりにh:message
属性を追加する必要がありました。そうでない場合は、それをそのまま参照する必要がありました。これは望ましい結果ではありませんでした。ident
id
<h:message for="captcha:captcha" />