開発者ドキュメント

JSF 2.0の複数コンポーネントバリデーター

JSFでは、複数のコンポーネントまたはフィールドを検証する公式な方法はありません。これを解決するには、カスタムバリデーターを作成する必要があります。このチュートリアルでは、パスワードと確認パスワードの複数のコンポーネントを検証するためのバリデータを作成する2つの非公式な方法を示します。

2つの方法:1. `PostValidateEvent`を登録し、内部に検証を入れます。 2.標準バリデータを作成し、 `f:attribute`を介して他のコンポーネントを取得します。

この例は、次のテクノロジでテストされています。

  1. JSF 2.1.11

  2. Tomcat 6,7

  3. Java 1.6

  4. Maven 3

1. PostValidateEventの検証

javax.faces.event.PostValidateEventは、すべてのコンポーネントが検証された後に起動するシステムイベントです。このアイデアは「PostValidateEvent」を登録し、検証メソッドにアタッチします。以下を参照してください:

<f:event listener="#{bean.methodToValidateMultipleFields}" type="postValidate"/>

default.xhtml

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
  xmlns:h="http://java.sun.com/jsf/html"
  xmlns:f="http://java.sun.com/jsf/core">

<h:body>

<h1>Multiple-Components Validator in JSF 2.0</h1>

  <h:form id="register">

    <h:message for="RegisterGroupPanel" style="color:red;"/>

    <h:panelGrid columns="3" id="RegisterGroupPanel">

    <!-- register a PostValidateEvent -->
    <f:event listener="#{user.validatePassword}" type="postValidate"/>

    <h:outputLabel for="username" value="Username : "/>
    <h:inputText id="username" value="#{user.username}" required="true"
        requiredMessage="Please enter username"/>
    <h:message for="username" style="color: red;"/>

    <h:outputLabel for="password" value="Password : "/>
    <h:inputSecret id="password" value="#{user.password}" required="true"
        requiredMessage="Please enter password"/>
    <h:message for="password" style="color: red;"/>

    <h:outputLabel for="confirmPassword" value="Confirm password : "/>
    <h:inputSecret id="confirmPassword" required="true"
        requiredMessage="Please enter confirm password"/>
    <h:message for="confirmPassword" style="color: red;"/>

    </h:panelGrid>

    <h:commandButton action="thanks" value="register"/>

  </h:form>

</h:body>
</html>


PostValidateEvent`では、" listener "メソッドはこの署名

public void method-name(ComponentSystemEvent event) `を持っていなければなりません。コードの残りの部分は自明です。

UserBean.java – パスワードを検証し、パスワードコンポーネントを確認するメソッドがあります。

package com.mkyong;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.event.ComponentSystemEvent;

@ManagedBean(name = "user")
@SessionScoped
public class UserBean {

    public String username;
    public String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void validatePassword(ComponentSystemEvent event) {

      FacesContext fc = FacesContext.getCurrentInstance();

      UIComponent components = event.getComponent();

     //get password
      UIInput uiInputPassword = (UIInput) components.findComponent("password");
      String password = uiInputPassword.getLocalValue() == null ? ""
        : uiInputPassword.getLocalValue().toString();
      String passwordId = uiInputPassword.getClientId();

     //get confirm password
      UIInput uiInputConfirmPassword = (UIInput) components.findComponent("confirmPassword");
      String confirmPassword = uiInputConfirmPassword.getLocalValue() == null ? ""
        : uiInputConfirmPassword.getLocalValue().toString();

     //Let required="true" do its job.
      if (password.isEmpty() || confirmPassword.isEmpty()) {
        return;
      }

      if (!password.equals(confirmPassword)) {

        FacesMessage msg = new FacesMessage("Password must match confirm password");
        msg.setSeverity(FacesMessage.SEVERITY__ERROR);
        fc.addMessage(passwordId, msg);
        fc.renderResponse();

      }

    }
}

2.カスタムバリデータ

このメソッドは、この記事(http://balusc.blogspot.com/2007/12/validator-for-multiple-fields.html[複数フィールドのバリデータ])からコピーされています。

“confirmPassword”コンポーネントを `#{confirmPassword}`として定義し、 `f:attribute`を介して” password “コンポーネントにアタッチします。

<h:inputSecret id="password" value="#{user.password}" required="true"
    requiredMessage="Please enter password">

    <f:validator validatorId="passwordValidator"/>
    <f:attribute name="confirmPassword" value="#{confirmPassword}"/>

</h:inputSecret>

<h:inputSecret id="confirmPassword" required="true"
    binding="#{confirmPassword}"
    requiredMessage="Please enter confirm password"/>

default.xhtml

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
  xmlns:h="http://java.sun.com/jsf/html"
  xmlns:f="http://java.sun.com/jsf/core">

<h:body>

  <h1>Multiple-Components Validator in JSF 2.0</h1>

  <h:form id="register">

    <h:message for="RegisterGroupPanel" style="color:red;"/>

    <h:panelGrid columns="3" id="RegisterGroupPanel">

    <h:outputLabel for="username" value="Username : "/>
    <h:inputText id="username" value="#{user.username}" required="true"
        requiredMessage="Please enter username"/>
    <h:message for="username" style="color: red;"/>

    <h:outputLabel for="password" value="Password : "/>
    <h:inputSecret id="password" value="#{user.password}" required="true"
        requiredMessage="Please enter password">
        <f:validator validatorId="passwordValidator"/>
        <f:attribute name="confirmPassword" value="#{confirmPassword}"/>
    </h:inputSecret>
    <h:message for="password" style="color: red;"/>

    <h:outputLabel for="confirmPassword" value="Confirm password : "/>
    <h:inputSecret id="confirmPassword" required="true"
        binding="#{confirmPassword}"
        requiredMessage="Please enter confirm password"/>
    <h:message for="confirmPassword" style="color: red;"/>

    </h:panelGrid>

    <h:commandButton action="thanks" value="register"/>

  </h:form>

</h:body>
</html>

カスタムバリデータクラス、 `component.getAttributes`で確認パスワードコンポーネントを取得します。

PasswordValidator.java – JSFカスタムバリデーター

package com.mkyong;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

@FacesValidator("passwordValidator")
public class PasswordValidator implements Validator {

    @Override
    public void validate(FacesContext context, UIComponent component,
        Object value) throws ValidatorException {

      String password = value.toString();

      UIInput uiInputConfirmPassword = (UIInput) component.getAttributes()
        .get("confirmPassword");
      String confirmPassword = uiInputConfirmPassword.getSubmittedValue()
        .toString();

     //Let required="true" do its job.
      if (password == null || password.isEmpty() || confirmPassword == null
        || confirmPassword.isEmpty()) {
            return;
      }

      if (!password.equals(confirmPassword)) {
        uiInputConfirmPassword.setValid(false);
        throw new ValidatorException(new FacesMessage(
            "Password must match confirm password."));
      }

    }
}

デモ

上記の2つのソリューションは同じことをしており、パスワードとパスワードを確認する2つのコンポーネントを検証します。

入力がなく、 `required =” true “`が実行されます。



複数のコンポーネント/フィールドを検証します。パスワードが確認パスワードと等しいことを確認してください。



ソースコードをダウンロードする

ダウンロードする – リンク://wp-content/uploads/2010/11/JSF-Validator-Multiple-Components-Example.zip[JSF-バリデーター – マルチプル – コンポーネント – サンプル.zip](27 KB)

モバイルバージョンを終了