電子媒体またはユーザの入力情報からデータを受け取る際に行われる、 それが妥当なデータかどうかのチェックは一般的(な処理)だと認識されています。 この処理は繰り返し行われ、また同じデータセットに対してロケール毎に異なった妥当性チェックのルールが 適用される場合等にはより複雑になってしまいます。 エラーメッセージもロケール毎に異なったものとなるでしょう。 このパッケージは上記問題を扱い、妥当性チェックの開発の効率化と保守性の向上を試みます。 {@primary A common issue when receiving data either electronically or from user input is verifying the integrity of the data. This work is repetitive and becomes even more complicated when different sets of validation rules need to be applied to the same set of data based on locale for example. Error messages may also vary by locale. This package attempts to address some of these issues and speed development and maintenance of validation rules. }
Validator を利用しようとする場合には、以下の基本的な手順を踏む必要があります: {@primary In order to use the Validator, the following basic steps are required:}
org.apache.commons.validator.Validator クラスインスタンスを生成します。
以前の妥当性チェックが完了していて、他のスレッドから同時にその Validator インスタンスを利用としない限り、
ValidatorResources が同じであれば現在の Validator インスタンスを再利用しても安全です。
{@primary Create a new instance of the
org.apache.commons.validator.Validator class. Currently
Validator instances may be safely reused if the current ValidatorResources
are the same, as long as
you have completed any previous validation, and you do not try to utilize
a particular Validator instance from more than one thread at a time.}org.apache.commons.validator.Validator の妥当性チェックメソッドを呼びます。
{@primary Call the validate method on org.apache.commons.validator.Validator.}Commons Validator はXMLファイルに定義された妥当性チェックのルールを JavaBean に対して行う基本的な妥当性チェックのためのフレームワークです。 妥当性チェックが定義された Validator はXMLファイルによって定義することができます。 Validator の例では "required(必須)" のフィールドに対する妥当性チェックの際にどのクラスのどのメソッドを呼ぶかを定義できます。 妥当性チェックのルールはロケール毎、ルールの適用される JavaBean/Form 毎にグループ化することができます。 このフレームワークでは慣用的に使用されるいくつかのフィールド属性(チェックのルール)をサポートします。 {@primary The Commons Validator is a basic validation framework that lets you define validation rules for a JavaBean in an xml file. Validators, the validation definition, can also be defined in the xml file. An example of a validator would be defining what method and class will be called to perform the validation for a required field. Validation rules can be grouped together based on locale and a JavaBean/Form that the rules are associated with. The framework has basic support for user defined constants which can be used in some field attributes. }
XMLファイルに定義され保持された妥当性チェックのルールは妥当性チェックの際に JavaBean に取り出されます。 Jakarta Commons BeanUtils (http://jakarta.apache.org/commons/beanutils.html) パッケージを使用し、階層構造をもったプロパティの参照をサポートします。 エラーメッセージとエラーメッセージ内の可変パラメータはフィールドの妥当性チェック処理と関連付けられます。 {@primary Validation rules can be defined in an xml file which keeps them abstracted from JavaBean you are validating. The property reference to a field supports nested properties using the Jakarta Commons BeanUtils (http://jakarta.apache.org/commons/beanutils.html) package. Error messages and the arguments for error messages can be associated with a fields validation.}
Validator インスタンスが生成された後、addResource メソッドを呼ぶことにより 妥当性チェックの処理を追加することができます。 以下に用意されたキー(とクラス名)を示します。 {@primary After a Validator instance is created, instances of classes can be added to it to be passed into validation methods by calling the addResource method. Below is a list of reserved keys (class names).}
| クラス名{@primary Class Name} | 内部リソースキー{@primary Validator Contant} | 内容{@primary Description} |
|---|---|---|
| java.lang.Object | Validator.BEAN_KEY | 妥当性チェックの対象となるJavaBean。 {@primary JavaBean that is being validated} |
| java.util.Locale | Validator.LOCALE_KEY | FormSet を取得する際のロケール。 指定されない場合にはデフォルトのロケールが使用されます。 {@primary Locale to use when retrieving a FormSet. The default locale will be used if one isn't specified.} |
| org.apache.commons.validator.ValidatorAction | Validator.VALIDATOR_ACTION_KEY | 妥当性チェックを行う際に Validator のリソースから自動的に追加されます。 この名称がメソッドにて指定された場合、指定された ValidatorAction が妥当性チェックの処理に追加されます。 {@primary This is automatically added to a Validator's resources as a validation is being processed. If this class name is used when defining a method signature for a pluggable validator, the current ValidatorAction will be passed into the validation method.} |
| org.apache.commons.validator.Field | Validator.FIELD_KEY | 妥当性チェックを行う際に Validator のリソースから自動的に追加されます。 この名称がメソッドにて指定された場合、指定された Field が妥当性チェックの処理対象に追加されます。 {@primary This is automatically added to a Validator's resources as a validation is being processed. If this class name is used when defining a method signature for a pluggable validator, the current Field will be passed into the validation method.} |
これは required (必須) の妥当性チェックルールをBeanに対して行う基本的な例です。
この例はユニットテスト内で使用されています ( validator/src/test にある
org.apache.commons.validator.RequiredNameTest と
validator-name-required.xml を参照してください)。
{@primary This is a basic example setting up a required validator for
a name bean. This example is a working unit test (reference
org.apache.commons.validator.RequiredNameTest and
validator-name-required.xml located under validator/src/test).}
妥当性チェックのルールと処理を定義したXMLファイルを作成します。
必要となる妥当性チェックをXMLファイルに定義してください。
{@primary Create an xml file with your validator and validation rules.
Setup your required validator in your xml file.}
XML Example
Validator Example
Pluggable Validator Example
"require(必須)" という入れ替え可能な妥当性チェックを定義します。
{@primary Definition of a 'required' pluggable validator.}
<form-validation>
<global>
<validator name="required"
classname="org.apache.commons.validator.TestValidator"
method="validateRequired"
methodParams="java.lang.Object,
org.apache.commons.validator.Field"/>
</global>
<formset>
</formset>
</form-validation>
"firstName" と "lastName" に "require(必須)" の妥当性チェックルールを追加します。
{@primary Add validation rules to require a first name and a last name.}
<form-validation>
<global>
<validator name="required"
classname="org.apache.commons.validator.TestValidator"
method="validateRequired"
methodParams="java.lang.Object,
org.apache.commons.validator.Field"/>
</global>
<formset>
<form name="nameForm">
<field property="firstName"
depends="required">
<arg0 key="nameForm.firstname.displayname"/>
</field>
<field property="lastName"
depends="required">
<arg0 key="nameForm.lastname.displayname"/>
</field>
</form>
</formset>
</form-validation>
org.apache.commons.validator.RequiredNameTest から抜粋 {@primary Excerpts from org.apache.commons.validator.RequiredNameTest}
InputStream in = this.getClass().getResourceAsStream("validator-name-required.xml");
// ValidatorResources インスタンスを
// XMLファイルにて初期化するために生成
{@primary // Create an instance of ValidatorResources to
// initialize from an xml file. }
ValidatorResources resources = new ValidatorResources();
// ValidatorResources 内にリソースをロード
{@primary // Load resources into ValidatorResources passed in }
ValidatorResourcesInitializer.initialize(resources, in);
// テスト対象となるBeanを生成
{@primary // Create bean to run test on.}
Name name = new Name();
// ロードされたリソースとフォームキーから
// 妥当性チェック(Validator)インスタンスを生成
{@primary // Construct validator based on the loaded resources
// and the form key}
Validator validator = new Validator(resources, "nameForm");
// 妥当性チェックを行うために
// 対象となるBeanを Validator に登録
{@primary // add the name bean to the validator as a resource
// for the validations to be performed on.}
validator.addResource(Validator.BEAN_KEY, name);
// 妥当性チェックの結果を取得
{@primary // Get results of the validation.}
Map hResults = null;
// ValidatorException が投げられるが
// この例では catch していない
{@primary // throws ValidatorException,
// but aren't catching for example}
hResults = validator.validate();
if (hResults.get("firstName") == null) {
// エラーなし
{@primary // no error}
} else {
// "firstName" に対するエラーの数
{@primary // number of errors for first name}
int errors = ((Integer)hResults.get("firstName")).intValue();
}
'required' 入れ替え可能な妥当性チェック内に定義された妥当性チェックメソッド (org.apache.commons.validator.TestValidator から抜粋)。 {@primary Validation method defined in the 'required' pluggable validator (excerpt from org.apache.commons.validator.TestValidator).}
public static boolean validateRequired(Object bean, Field field) {
String value = ValidatorUtil.getValueAsString(bean, field.getProperty());
return GenericValidator.isBlankOrNull(value);
}