快速背景:我已在我的網站上使用primefaces自定義組件添加驗證碼。負責人不喜歡它,因爲它太難使用,客戶抱怨。我決定創建一個簡單的組件(例如:4 + 9 =並且用戶輸入答案)以避免一些垃圾郵件。無需使用簡單的文本就可以顯示圖像。這讓我看着自定義組件和複合組件(從this article和this one)。需要交互/驗證的表單中的複合組件
現在,問題不在於一個臨時的基本「驗證碼樣式驗證」。這更多的是關於複合組件和支持豆組合。
我會怎麼做,在這種風格創建支持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
如果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" />
這不是預期的結果。
我會在captcha' backing bean中寫一個自定義[驗證方法](http://docs.oracle.com/javaee/6/tutorial/doc/bnavb.html#bave),並將它添加到'captchaAnswer'輸入。你試過這個嗎? –
@PiotrGwiazda編輯添加了你的想法的問題。沒有雪茄。 – blo0p3r
如前所述,把這個驗證器放在'