バリデータ

□未翻訳

□翻訳中

■翻訳完了(細田謙二)

■レビュー(Omi Chiba)

バリデータ

バリデータは入力フィールド(データベース・テーブルから生成されたフォームを含む)を検証するために使用するクラスです。

Validators are classes used to validate input fields (including forms generated from database tables).

FORMとともにバリデータを使用する例です:

Here is an example of using a validator with a FORM:

1.

INPUT(_name='a', requires=IS_INT_IN_RANGE(0, 10))

どのようにテーブルのフィールドに対するバリデータを要求するかの例です:

Here is an example of how to require a validator for a table field:

1.

2.

db.define_table('person', Field('name'))

db.person.name.requires = IS_NOT_EMPTY()

バリデータは常にフィールドのrequires属性を用いて割り当てられます。フィールドは、単一もしくは複数のバリデータを持つことができます。複数のバリデータはリストの一部になります:

Validators are always assigned using the requires attribute of a field. A field can have a single validator or multiple validators. Multiple validators are made part of a list:

1.

2.

db.person.name.requires = [IS_NOT_EMPTY(),

IS_NOT_IN_DB(db, 'person.name')]

バリデータはFORM上のaccepts関数や、フォームを含む他のHTMLヘルパーオブジェクトによって呼ばれます。それらは、列挙されている順序で呼ばれます。

Validators are called by the function accepts on a FORM or other HTML helper object that contains a form. They are called in the order in which they are listed.

組み込みのバリデータはオプション引数を取るコンストラクタを持っています:

Built-in validators have constructors that take an optional argument:

1.

IS_NOT_EMPTY(error_message=T('cannot be empty'))

error_messageは、任意のバリデータに対してデフォルトのエラーメッセージをオーバーライドするようにします。

error_message allows you to override the default error message for any validator.

データベース・テーブルに対するバリデータの例です:

Here is an example of a validator on a database table:

1.

db.person.name.requires = IS_NOT_EMPTY(error_message=T('fill this!'))

ここで、国際化対応のためTという翻訳演算子を使用しています。なお、デフォルトのエラーメッセージは翻訳されません。

where we have used the translation operator T to allow for internationalization. Notice that default error messages are not translated.

バリデータ

Validators

IS_ALPHANUMERIC

このバリデータは、フィールドの値がa~z、A~Z、0~9の範囲にある文字しか含まれていないことをチェックします。

This validator checks that a field value contains only characters in the ranges a-z, A-Z, or 0-9.

1.

requires = IS_ALPHANUMERIC(error_message=T('must be alphanumeric!'))

IS_DATE

このバリデータは、指定したフォーマットで有効な日付がフィールドの値に入っていることをチェックします。異なるローケルで異なるフォーマットをサポートするために、翻訳演算子を用いてフォーマットを指定するのは良いプラクティスです。

This validator checks that a field value contains a valid date in the specified format. It is good practice to specify the format using the translation operator, in order to support different formats in different locales.

1.

2.

requires = IS_DATE(format=T('%Y-%m-%d'),

error_message=T('must be YYYY-MM-DD!'))

%ディレクティブの詳細な説明はIS_DATETIMEバリデータの項目を参照してください。

For the full description on % directives look under the IS_DATETIME validator.

IS_DATE_IN_RANGE

前のバリデータと非常に似ていますが、範囲を指定することができます:

Works very much like the previous validator but allows to specify a range:

1.

2.

3.

4.

requires = IS_DATE_IN_RANGE(format=T('%Y-%m-%d'),

minimum=datetime.date(2008,1,1),

maximum=datetime.date(2009,12,31),

error_message=T('must be YYYY-MM-DD!'))

%ディレクティブの詳細な説明はIS_DATETIMEバリデータの項目を参照してください。

For the full description on % directives look under the IS_DATETIME validator.

IS_DATETIME

このバリデータは、指定したフォーマットで有効な日時がフィールドの値に入っていることをチェックします。異なるローケルで異なるフォーマットをサポートするために、翻訳演算子を用いてフォーマットを指定するのは良いプラクティスです。

This validator checks that a field value contains a valid datetime in the specified format. It is good practice to specify the format using the translation operator, in order to support different formats in different locales.

1.

2.

requires = IS_DATETIME(format=T('%Y-%m-%d %H:%M:%S'),

error_message=T('must be YYYY-MM-DD HH:MM:SS!'))

以下のシンボルをフォーマット文字列に対して使用することができます(シンボルと例となる文字列を示します):

The following symbols can be used for the format string (this shows the symbol and an example string):

1.

2.

3.

4.

5.

6.

7.

8.

9.

10.

11.

%Y '1963'

%y '63'

%d '28'

%m '08'

%b 'Aug'

%b 'August'

%H '14'

%I '02'

%p 'PM'

%M '30'

%S '59'

IS_DATETIME_IN_RANGE

前のバリデータと非常に似ていますが、範囲を指定することができます:

Works very much like the previous validator but allows to specify a range:

1.

2.

3.

4.

requires = IS_DATETIME_IN_RANGE(format=T('%Y-%m-%d %H:%M:%S'),

minimum=datetime.datetime(2008,1,1,10,30),

maximum=datetime.datetime(2009,12,31,11,45),

error_message=T('must be YYYY-MM-DD HH:MM::SS!'))

%ディレクティブの詳細な説明はIS_DATETIMEバリデータの項目を参照してください。

For the full description on % directives look under the IS_DATETIME validator.

IS_DECIMAL_IN_RANGE

1.

INPUT(_type='text', _name='name', requires=IS_DECIMAL_IN_RANGE(0, 10))

入力をPythonのDecimalへと変換します。もしくは、数値が指定した範囲に収まっていない場合はエラーを生成します。比較はPythonのDecimalの算術で行われます。

It converts the input into a Python Decimal or generates an error if the decimal does not fall within the specified inclusive range. The comparison is made with Python Decimal arithmetic.

最小値と最大値にはNoneを設定することができ、それぞれ。下限なし、上限なしを意味します。

The minimum and maximum limits can be None, meaning no lower or upper limit, respectively.

IS_EMAIL

フィールドの値がemailのアドレスのようになっているかをチェックします。確認のためemailを送信することは試みません。

It checks that the field value looks like an email address. It does not try to send email to confirm.

1.

requires = IS_EMAIL(error_message=T('invalid email!'))

IS_EQUAL_TO

検証された値が与えられた値(変数にすることもできます)と等しいかチェックします:

Checks whether the validated value is equal to a given value (which can be a variable):

1.

2.

requires = IS_EQUAL_TO(request.vars.password,

error_message=T('passwords do not match'))

IS_EXPR

最初の引数は、変数に値に関する論理的な表現を保持する文字列です。フィールドの値を、その式がTrueに評価されるかどうかで検証します。例:

Its first argument is a string containing a logical expression in terms of a variable value. It validates a field value if the expression evaluates to True. For example:

1.

2.

requires = IS_EXPR('int(value)%3==0',

error_message=T('not divisible by 3'))

例外が発生しないように、初めに整数であることをチェックしたほうがよいでしょう。

One should first check that the value is an integer so that an exception will not occur.

1.

requires = [IS_INT_IN_RANGE(0, 100), IS_EXPR('value%3==0')]

IS_FLOAT_IN_RANGE

フィールドの値が範囲内の浮動小数点になっていることをチェックします。次の例では、0 <= value <= 100 の範囲をチェックしています:

Checks that the field value is a floating point number within a definite range, 0 <= value <= 100 in the following example:

1.

2.

requires = IS_FLOAT_IN_RANGE(0, 100,

error_message=T('too small or too large!'))

IS_INT_IN_RANGE

フィールドの値が範囲内の整数になっていることをチェックします。次の例では、0 <= value <= 100 の範囲をチェックしています:

Checks that the field value is an integer number within a definite range, 0 <= value < 100 in the following example:

1.

2.

requires = IS_INT_IN_RANGE(0, 100,

error_message=T('too small or too large!'))

IS_IN_SET

フィールドの値がセットに含まれていることをチェックします:

Checks that the field values are in a set:

1.

2.

requires = IS_IN_SET(['a', 'b', 'c'],zero=T('choose one'),

error_message=T('must be a or b or c'))

zero引数は省略可能で、デフォルトで選択されたオプション、つまり、IS_IN_SETバリデータ自身によって受理されないオプション、のテキストを決めます。"chooose one"オプションを望まない場合は、zero=Noneとしてください。

The zero argument is optional and it determines the text of the option selected by default, an option which is not accepted by the IS_IN_SET validator itself. If you do not want a "choose one" option, set zero=None.

zeroオプションはリビジョン(1.67.1)において導入されました。これは、アプリケーションを壊さないという意味で後方互換性を破りませんでした。しかし、以前はzeroオプションがなかったので、その挙動は変化しました。

The zero option was introduced in revision (1.67.1). It did not break backward compatibility in the sense that it did not break applications but it did change their behavior since, before, there was no zero option.

セットの要素は常に文字列でなければなりません。ただし、このバリデータがIS_INT_IN_RANGE(値をintに変換)かIS_FLOAT_RANGE(値をfloatに変換)の後に続く場合はその限りではありません。例:

The elements of the set must always be strings unless this validator is preceded byIS_INT_IN_RANGE (which converts the value to int) or IS_FLOAT_IN_RANGE (which converts the value to float). For example:

1.

2.

requires = [IS_INT_IN_RANGE(0, 8), IS_IN_SET([2, 3, 5, 7],

error_message=T('must be prime and less than 10'))]

また、ドロップダウンのリストをより記述的にするために、次のように辞書かタプルのリストを用いることもできます:

You may also use a dictionary or a list of tuples to make the drop down list more descriptive:

1.

2.

3.

4.

### Dictionary example:

requires = IS_IN_SET({'A':'Apple','B':'Banana','C':'Cherry'},zero=None)

### List of Tuples example:

requires = IS_IN_SET([('A','Apple'),('B','Banana'),('C','Cherry')])

IS_IN_SETとタグ付け

IS_IN_SET and Tagging

IS_IN_SETバリデータはmultiple=Falseというオプション属性を持ちます。これがTrueに設定されている場合、複数の値を1つのフィールドに格納することができます。フィールドの型は、list:integerかlist:stringにしてください。multiple参照は、作成と更新フォームにおいて自動的に処理されます。しかし、DALに対して透過的ではありません。multipleフィールドをレンダリングするためには、jQueryのmultiselectプラグインを使用することを強く勧めます。

The IS_IN_SET validator has an optional attribute multiple=False. If set to True, multiple values can be stored in one field. The field should be of type list:integer or list:string.multiple references are handled automatically in create and update forms, but they are transparent to the DAL. We strongly suggest using the jQuery multiselect plugin to render multiple fields.

multiple=Trueのとき、IS_IN_SETはzeroか複数の値を受け入れることに注意してください。つまり、何も選択されていないときも受理されます。

Note that when multiple=True, IS_IN_SET will accept zero or more values, i.e. it will accept the field when nothing has been selected.

IS_LENGTH

フィールドの値の長さが与えられた境界の間に収まることをチェックします。テキストとファイルの入力の両方で機能します。

Checks if length of field's value fits between given boundaries. Works for both text and file inputs.

引数は次の通りです:

Its arguments are:

  • maxsize: 最大許容の長さ/サイズ(デフォルトは255)

    • the maximum allowed length / size (has default = 255)

  • minsize: 最小許容の長さ/サイズ

    • the minimum allowed length / size

例:テキストの文字列が33文字よりも短いかをチェックします:

Examples: Check if text string is shorter than 33 characters:

1.

INPUT(_type='text', _name='name', requires=IS_LENGTH(32))

例:テキストの文字列が5文字よりも長いかをチェックします:

Check if password string is longer than 5 characters:

1.

INPUT(_type='password', _name='name', requires=IS_LENGTH(minsize=6))

アップロードされたファイルのサイズが1KBと1MBの間にあるかをチェックします:

Check if uploaded file has size between 1KB and 1MB:

1.

INPUT(_type='file', _name='name', requires=IS_LENGTH(1048576, 1024))

ファイルを除くすべてのフィールドの型に対して、値の長さをチェックします。ファイルの場合は、値はcookie.FieldStorageになります。したがって、直感的に予想できる挙動であるファイルのデータ長をチェックすることになります。

For all field types except for files, it checks the length of the value. In the case of files, the value is a cookie.FieldStorage, so it validates the length of the data in the file, which is the behavior one might intuitively expect.

IS_LIST_OF

これは適切なバリデータではありません。その使用目的は、複数の値を返すフィールドの検証を可能にすることです。フォームが同じ名前の複数のフィールドや複数選択ボックスを含む場合といった稀なケースにおいて使用されます。唯一の引数は、別のバリデータです。別のバリデータをリストの各要素に適用することしかしません。たとえば、次の式はリストの各項目が0~10の範囲にある整数であることをチェックします:

This is not properly a validator. Its intended use is to allow validations of fields that return multiple values. It is used in those rare cases when a form contains multiple fields with the same name or a multiple selection box. Its only argument is another validator, and all it does is to apply the other validator to each element of the list. For example, the following expression checks that every item in a list is an integer in the range 0-10:

1.

requires = IS_LIST_OF(IS_INT_IN_RANGE(0, 10))

これは、エラーを返すことはなく、エラーメッセージも含まれません。内部のバリデータがエラーの発生を制御します。

It never returns an error and does not contain an error message. The inner validator controls the error generation.

IS_LOWER

このバリデータは決してエラーを返しません。単に、値を小文字に変換します。

This validator never returns an error. It just converts the value to lower case.

1.

requires = IS_LOWER()

IS_MATCH

このバリデータは、値を正規表現と照合し、一致してない場合はエラーを返します。米国の郵便番号を検証する使用例を示します:

This validator matches the value against a regular expression and returns an error if it does not match. Here is an example of usage to validate a US zip code:

1.

2.

requires = IS_MATCH('^\d{5}(-\d{4})?$',

error_message='not a zip code')

IPv4アドレスを検証する使用例です(ただし、IS_IPV4バリデータのほうがこの目的のためにはより妥当です):

Here is an example of usage to validate an IPv4 address (note: the IS_IPV4 validator is more appropriate for this purpose):

1.

2.

requires = IS_MATCH('^\d{1,3}(\.\d{1,3}){3}$',

error_message='not an IP address')

米国の電話番号を検証するための使用例です:

Here is an example of usage to validate a US phone number:

1.

2.

requires = IS_MATCH('^1?((-)\d{3}-?|\(\d{3}\))\d{3}-?\d{4}$',

error_message='not a phone number')

Pythonの正規表現の詳細については、公式のPythonのマニュアルを参照してください。

For more information on Python regular expressions, refer to the official Python documentation.

IS_NOT_EMPTY

このバリデータは、フィールドの値が空の文字列ではないことをチェックします。

This validator checks that the content of the field value is not an empty string.

1.

requires = IS_NOT_EMPTY(error_message='cannot be empty!')

IS_TIME

このバリデータは、指定したフォーマットでの有効な時間がフィールドの値に入力されていることをチェックします。

This validator checks that a field value contains a valid time in the specified format.

1.

requires = IS_TIME(error_message=T('must be HH:MM:SS!'))

IS_URL

次のいずれかに該当するURL文字列を拒否します:

Rejects a URL string if any of the following is true:

  • 文字列が空またはNone

    • The string is empty or None

  • 文字列がURLで許可されていない文字を使用する

    • The string uses characters that are not allowed in a URL

  • 文字列がHTTP構文規則のいずれかを破る

    • The string breaks any of the HTTP syntactic rules

  • (指定した場合)URLのスキームが'http'か'https'でない

    • The URL scheme specified (if one is specified) is not 'http' or 'https'

  • (ホスト名を指定した場合)トップレベルのドメインが存在しない

    • The top-level domain (if a host name is specified) does not exist

(これらの規則は、RFC 2616に基づいています)

(These rules are based on RFC 261665 )

この関数はURLの構文をチェックすることしかしません。URLが、たとえば実際の文章を指していることや、語義的に理にかなっていことはチェックしません。この関数は、省略URL('google.ca'など)の場合、自動的にURLの前に'http://'を追加します。

This function only checks the URL's syntax. It does not check that the URL points to a real document, for example, or that it otherwise makes semantic sense. This function does automatically prepend 'http://' in front of a URL in the case of an abbreviated URL (e.g. 'google.ca').

mode='generic'というパラメータが使用されている場合、この関数の挙動は変化します。このときは、次のいずれかに該当するURL文字列を拒否します:

If the parameter mode='generic' is used, then this function's behavior changes. It then rejects a URL string if any of the following is true:

  • 文字列が空またはNone

    • The string is empty or None

  • 文字列がURLで許可されていない文字を使用する

    • The string uses characters that are not allowed in a URL

  • (指定した場合)URLのスキームが有効でない

    • The URL scheme specified (if one is specified) is not valid

(これらの規則は、RFC 2396に基づいています)

(These rules are based on RFC 239666 )

許可されたスキーマのリストはallowed_schemesパラメータを使用してカスタマイズすることができます。リストからNoneを取り除いた場合、('http'のようなスキームを欠く)省略URLは拒否されます。

The list of allowed schemes is customizable with the allowed_schemes parameter. If you exclude None from the list, then abbreviated URLs (lacking a scheme such as 'http') will be rejected.

デフォルトで先頭に追加されるスキーマはprepend_schemeパラメータでカスタマイズすることができます。prepend_schemeをNoneに設定した場合、先頭への追加は無効になります。それでも、解析のために先頭への追加が必要なURLは受け入れられますが、戻り値は変更されません。

The default prepended scheme is customizable with the prepend_scheme parameter. If you set prepend_scheme to None, then prepending will be disabled. URLs that require prepending to parse will still be accepted, but the return value will not be modified.

IS_URLは、RFC 3490で指定されている国際化ドメイン名(IDN)の標準と互換性があります。その結果、URLには、通常の文字列またはUnicode文字列を指定できます。URLのドメイン・コンポーネント(たとえば、google.ca)が非US-ASCII文字を含んでいる場合、ドメインは(RFC 3492で定義された)Punycodeに変換されます。IS_URLは標準を少しだけ越えて、非US-ASCII文字がURLのパスとクエリのコンポーネントにも提示されることを許可しています。これらの非US-ASCII文字はエンコードされます。たとえば、スペースは、'%20'にエンコードされます。16進数のUnicode文字0x4e86は'%4e%86'になります。

IS_URL is compatible with the Internationalized Domain Name (IDN) standard specified in RFC 349067 ). As a result, URLs can be regular strings or unicode strings. If the URL's domain component (e.g. google.ca) contains non-US-ASCII letters, then the domain will be converted into Punycode (defined in RFC 349268 ). IS_URL goes a bit beyond the standards, and allows non-US-ASCII characters to be present in the path and query components of the URL as well. These non-US-ASCII characters will be encoded. For example, space will be encoded as'%20'. The unicode character with hex code 0x4e86 will become '%4e%86'.

例:

Examples:

1.

2.

3.

4.

5.

6.

7.

requires = IS_URL())

requires = IS_URL(mode='generic')

requires = IS_URL(allowed_schemes=['https'])

requires = IS_URL(prepend_scheme='https')

requires = IS_URL(mode='generic',

allowed_schemes=['ftps', 'https'],

prepend_scheme='https')

IS_SLUG

1.

requires = IS_SLUG(maxlen=80, check=False, error_message='must be slug')

checkがTrueに設定されている場合、検証される値が(英数字と繰り返しなしのダッシュのみ許可する)スラグかどうかをチェックします。

If check is set to True it check whether the validated value is a slug (allowing only alphanumeric characters and non-repeated dashes).

checkがFalseの場合(デフォルト)、入力値をスラグに変換します。

If check is set to False (default) it converts the input value to a slug.

IS_STRONG

フィールド(通常はパスワードフィールド)の複雑さの要求を強制します。

Enforces complexity requirements on a field (usually a password field)

例:

Example:

1.

requires = IS_STRONG(min=10, special=2, upper=2)

ここで、

where

  • minは値の最小の長さです

    • min is minimum length of the value

  • specialは要求される特殊文字の最小数です。特殊文字は、次のいずれかなります@#$%^&*(){}[]-+

  • special is the minimum number of required special characters special characters are any of the followiing !@#$%^&*(){}[]-+

  • upperは大文字の最小数です

    • upper is the minimum number of upper case characters

IS_IMAGE

このバリデータは、ファイル入力からアップロードされたファイルが選択した画像のフォーマットの1つで保存されているか、また、与えられた制約内の寸法(幅と高さ)を持っているかどうかをチェックします。

This validator checks if a file uploaded through the file input was saved in one of the selected image formats and has dimensions (width and height) within given limits.

これは、最大ファイルサイズはチェックしていません(そのためにはIS_LENGTHを使用してください)。何もデータがアップロードされていない場合は、検証エラーを返します。BMP、GIF、JPEG、PNGのファイル形式をサポートしています。Python Imaging Libraryは必要ありません。

It does not check for maximum file size (use IS_LENGTH for that). It returns a validation failure if no data was uploaded. It supports the file formats BMP, GIF, JPEG, PNG, and it does not require the Python Imaging Library.

コードの一部は参照から取っています。

Code parts taken from ref.69

次の引数を取ります:

It takes the following arguments:

  • extensions: 許可する小文字の画像ファイル拡張子を保持する反復可能オブジェクト

    • iterable containing allowed image file extensions in lowercase

  • maxsize: 画像の最大の幅と高さを保持する反復可能オブジェクト

    • iterable containing maximum width and height of the image

  • minsize: 画像の最小の幅と高さを保持する反復可能オブジェクト

    • iterable containing minimum width and height of the image

画像サイズのチェックを回避するには、minsizeとして(-1, -1)を使用してください。

Use (-1, -1) as minsize to bypass the image-size check.

いくつかの例を示します:

Here are some Examples:

  • アップロードされたファイルがサポートされている画像フォーマットのいずれかに含まれるかをチェックします:

    • Check if uploaded file is in any of supported image formats:

1.

requires = IS_IMAGE()

  • アップロードされたファイルがJPEGまたはPNG形式かをチェックします:

    • Check if uploaded file is either JPEG or PNG:

1.

requires = IS_IMAGE(extensions=('jpeg', 'png'))

  • アップロードされたファイルが最大200x200ピクセルのサイズのPNGであるかをチェックします:

    • Check if uploaded file is PNG with maximum size of 200x200 pixels:

1.

requires = IS_IMAGE(extensions=('png'), maxsize=(200, 200))

  • 注:requires = IS_IMAGE()を含むテーブルに対する編集フォームを表示するとき、deleteチェックボックスは現れません。なぜなら、ファイルを削除すると検証エラーになるからです。deleteチェックボックスを表示するには、次のバリデーションを使用してください:

  • Note: on displaying an edit form for a table including requires = IS_IMAGE(), a deletecheckbox will NOT appear because to delete the file would cause the validation to fail. To display the delete checkbox use this validation:

1.

requires = IS_EMPTY_OR(IS_IMAGE())

IS_UPLOAD_FILENAME

このバリデータは、ファイル入力からアップロードされたファイルの名前と拡張子が与えられた条件に一致するかをチェックします。

This validator checks if the name and extension of a file uploaded through the file input matches the given criteria.

どのような方法であれ、これはファイルの型を保証するものではありません。何もデータがアップロードされていない場合は、検証エラーを返します。

It does not ensure the file type in any way. Returns validation failure if no data was uploaded.

引数は次の通りです:

Its arguments are:

  • filename: (ドットの前の)ファイル名の正規表現です。

    • filename (before dot) regex.

  • extension: (ドットの後の)拡張子の正規表現です。

    • extension (after dot) regex.

  • lastdot: どのドットがファイル名/拡張子の区分に使用されるか:Trueの場合、最後のドットとなります(たとえば、"file.tar.gz"は"file.tar"+"gz"に分解されます)。一方Falseの場合、最初のドットになります(たとえば、"file.tar.gz"は"file"+"tar.gz"に分解されます)。

    • which dot should be used as a filename / extension separator: True indicates last dot (e.g., "file.tar.gz" will be broken in "file.tar"+"gz") while False means first dot (e.g., "file.tar.gz" will be broken into "file"+"tar.gz).

  • case: 0は大文字小文字を維持します。1は文字列を小文字に変換します(デフォルト)。2は文字列を大文字に変換します。

    • 0 means keep the case,; 1 means transform the string into lowercase (default); 2 means transform the string into uppercase.

dotが存在しない場合、拡張子は空の文字列に対してチェックされ、ファイル名はすべての文字列に対してチェックされます。

If there is no dot present, extension checks will be done against an empty string and filename checks will be done against the whole value.

例:

Examples:

ファイルがpdfの拡張子を持つかをチェックします(大文字小文字は区別しません):

Check if file has a pdf extension (case insensitive):

1.

requires = IS_UPLOAD_FILENAME(extension='pdf')

ファイルがtar.gz拡張子を持ち、かつ、backupで始まる名前を持つかをチェックします:

Check if file has a tar.gz extension and name starting with backup:

1.

requires = IS_UPLOAD_FILENAME(filename='backup.*', extension='tar.gz', lastdot=False)

ファイルが、拡張子を持たず、かつ、名前がREADMEに一致するかをチェックします(大文字小文字を区別します):

Check if file has no extension and name matching README (case sensitive):

1.

requires = IS_UPLOAD_FILENAME(filename='^README$', extension='^$', case=0)

IS_IPV4

このバリデータは、フィールドの値が10進数形式のIPバージョン4のアドレスかをチェックします。特定の範囲のアドレスに強制するように設定できます。

This validator checks if a field's value is an IP version 4 address in decimal form. Can be set to force addresses from a certain range.

IPv4の正規表現は参照から取っています。引数は以下の通りです。

IPv4 regex taken from ref.70 Its arguments are:

  • minip 許容する最下限のアドレス。str(例:192.168.0.1)や、反復可能な数字(例:[192, 168, 0, 1])や、int(例:3232235521)を受け入れます。

    • lowest allowed address; accepts: str, e.g., 192.168.0.1; iterable of numbers, e.g., [192, 168, 0, 1]; int, e.g., 3232235521

  • maxip 許容する最上限のアドレス。上と同様に受け入れます。

    • highest allowed address; same as above

ここにある3つの例の値は同じです。アドレスは、次の関数で包含チェックをするために、整数に変換されるからです:

All three example values are equal, since addresses are converted to integers for inclusion check with following function:

1.

number = 16777216 * IP[0] + 65536 * IP[1] + 256 * IP[2] + IP[3]

例:

Examples:

有効なIPv4のアドレスに対するチェックをします:

Check for valid IPv4 address:

1.

requires = IS_IPV4()

有効なプライベートネットワークのIPv4のアドレスに対するチェックをします:

Check for valid private network IPv4 address:

1.

requires = IS_IPV4(minip='192.168.0.1', maxip='192.168.255.255')

IS_LOWER

このバリデータはエラーを返すことはありません。値を小文字に変換します。

This validator never returns an error. It converts the value to lower case.

1.

requires = IS_LOWER()

IS_UPPER

このバリデータはエラーを返すことはありません。値を大文字に変換します。

This validator never returns an error. It converts the value to upper case.

1.

requires = IS_UPPER()

IS_NULL_OR

非推奨のもので、下に記述するIS_EMPTY_ORの別名です。

Deprecated, an alias for IS_EMPTY_OR described below.

IS_EMPTY_OR

他の要求と一緒にフィールに空の値を許可したい場合があります。たとえば、フィールドは日付だが、空の値にもなりうるという場合です。IS_EMPTY_ORバリデータはこれを可能にします:

Sometimes you need to allow empty values on a field along with other requirements. For example a field may be a date but it can also be empty. The IS_EMPTY_OR validator allows this:

1.

requires = IS_EMPTY_OR(IS_DATE())

CLEANUP

これはフィルタです。失敗することはありません。単に、[10、13、32〜127]のリストに含まれない10進数のASCIIコードを持つすべての文字を削除します。

This is a filter. It never fails. It just removes all characters whose decimal ASCII codes are not in the list [10, 13, 32-127].

1.

requires = CLEANUP()

CRYPT

これもフィルタです。入力に対して安全なハッシュを実行します。パスワードがデータベースに明白に渡されるのを防ぐのに使用されます。

This is also a filter. It performs a secure hash on the input and it is used to prevent passwords from being passed in the clear to the database.

1.

requires = CRYPT()

keyが指定されていない場合、MD5アルゴリズムが使用されます。keyが指定されている場合、CRYPTはHMACアルゴリズムを用います。keyには、HMACとともに使用するアルゴリズムを決める接頭辞を含めることも可能です。たとえば、SHA512は次のようになります:

If a key is not specified, it uses the MD5 algorithm. If a key is specified CRYPT uses the HMAC algorithm. The key may contain a prefix that determines the algorithm to use with HMAC, for example SHA512:

1.

requires = CRYPT(key='sha512:thisisthekey')

これは、推奨される構文です。keyは、使用されるデータベースに関連付けられた一意の文字列でなければなりません。keyは変更することはできません。keyを失うと、それ以前にハッシュ化された値は使用できなくなります。

This is the recommended syntax. The key has to be a unique string associated to the database used. The key can never be changed. If you lose the key the previously hashed values become useless.

Database Validators

IS_NOT_IN_DB

次の例を考えます:

Consider the following example:

1.

2.

db.define_table('person', Field('name'))

db.person.name.requires = IS_NOT_IN_DB(db, 'person.name')

これは、新規のpersonを挿入したとき、彼/彼女の名前がデータベース、dbに、すなわち、フィールドperson.nameにすでに存在していないことを要求します。他のバリデータと同様、この要求はフォーム処理のレベルで強制され、データベースレベルではされません。これには次のわずかな可能性があります。2人の訪問者が同時に、同じperson.nameを持つレコードを挿入しようとした場合、競合状態を引き起こし、両者のレコードが受け入れられてしまうことです。したがって、データベースに対しても、このフィールドが一意の値を持つということを知らせるほうが安全です:

It requires that when you insert a new person, his/her name is not already in the database, db, in the field person.name. As with all other validators this requirement is enforced at the form processing level, not at the database level. This means that there is a small probability that, if two visitors try to concurrently insert records with the same person.name, this results in a race condition and both records are accepted. It is therefore safer to also inform the database that this field should have a unique value:

1.

2.

db.define_table('person', Field('name', unique=True))

db.person.name.requires = IS_NOT_IN_DB(db, 'person.name')

このとき、競合状態が発生した場合、データベースはOperationalErrorを発生させ、2つのうちの1つの挿入が拒否されます。

Now if a race condition occurs, the database raises an OperationalError and one of the two inserts is rejected.

IS_NOT_IN_DBの最初の引数は、データベース接続かSetにすることができます。後者の場合、Setで定義されたセットのみをチェックするようになります。

The first argument of IS_NOT_IN_DB can be a database connection or a Set. In the latter case, you would be checking only the set defined by the Set.

次のコードは、たとえば、互いに10日以内に同じ名前を持つ2人のpersonsの登録を許可しません:

The following code, for example, does not allow registration of two persons with the same name within 10 days of each other:

1.

2.

3.

4.

5.

6.

7.

import datetime

now = datetime.datetime.today()

db.define_table('person',

Field('name'),

Field('registration_stamp', 'datetime', default=now))

recent = db(db.person.registration_stamp>now-datetime.timedelta(10))

db.person.name.requires = IS_NOT_IN_DB(recent, 'person.name')

IS_IN_DB

次のテーブルと要求を考えてください:

Consider the following tables and requirement:

1.

2.

3.

4.

db.define_table('person', Field('name', unique=True))

db.define_table('dog', Field('name'), Field('owner', db.person)

db.dog.owner.requires = IS_IN_DB(db, 'person.id', '%(name)s',

zero=T('choose one'))

これは、dogの挿入/更新/削除フォームのレベルで強制されます。これは、dog.ownerがdbデータベースのperson.idフィールドにおいて有効なidになっていることを要求します。このバリデータのおかげで、dog.ownerフィールドはドロップボックスによって表現されます。バリデータの3番目の引数は、ドロップボックスの内の要素を説明する文字列です。この例では、personの%(id)sの代わりに、personの%(name)sを見たいことになります。%(...)sは、各レコードに対して括弧内においてフィールドの値によって置き換えられます。

It is enforced at the level of dog INSERT/UPDATE/DELETE forms. It requires that adog.owner be a valid id in the field person.id in the database db. Because of this validator, thedog.owner field is represented as a dropbox. The third argument of the validator is a string that describes the elements in the dropbox. In the example you want to see the person%(name)s instead of the person %(id)s. %(...)s is replaced by the value of the field in brackets for each record.

zeroオプションはIS_IN_SETバリデータに対するものと非常によく似た動作をします。

The zero option works very much like for the IS_IN_SET validator.

このバリデータの最初の引数は、IS_NOT_IN_DBの場合と同様に、データベース接続かSetにすることができます。これはたとえば、ドロップボックス内のレコードを制限したいときに活用できます。次の例では、コントローラ内でIS_IN_DBを用いて、コントローラが呼ばれるたびに動的にレコードを制限しています:

The first argument of the validator can be a database connection or a DAL Set, as inIS_NOT_IN_DB. This can be useful for example when wishing to limit the records in the drop-down box. In this example, we use IS_IN_DB in a controller to limit the records dynamically each time the controller is called:

1.

2.

3.

4.

5.

6.

7.

def index():

(...)

query = (db.table.field == 'xyz') #in practice 'xyz' would be a variable

db.table.field.requires=IS_IN_DB(db(query),....)

form=SQLFORM(...)

if form.accepts(...)

(...)

フィールドの検証はしたいが、ドロップボックスを表示したくない場合、バリデータをリストの中に置いてください。

If you want the field validated, but you do not want a dropbox, you must put the validator in a list.

1.

db.dog.owner.requires = [IS_IN_DB(db, 'person.id', '%(name)s')]

場合によっては、ドロップボックスは使用したが(上のようにはリスト構文を用いたくないことになります)、追加のバリデータを使用したいときがあります。この目的のために、IS_IN_DBバリデータは_andという追加の引数をとります。これは、検証値がIS_IN_DBの検証を通った場合に適用される他のバリデータのリストを指します。たとえば、db内のすべてのdogのownersにおいて、あるサブセットにはないことを検証するためには次のようにします:

Occasionally you want the drop-box (so you do not want to use the list syntax above) yet you want to use additional validators. For this purpose the IS_IN_DB validator takes an extra argument _and that can point to a list of other validators applied if the validated value passes the IS_IN_DB validation. For example to validate all dog owners in db that are not in a subset:

1.

2.

3.

subset=db(db.person.id>100)

db.dog.owner.requires = IS_IN_DB(db, 'person.id', '%(name)s',

_and=IS_NOT_IN_DB(subset,'person.id'))

IS_IN_DBとタグ付け

IS_IN_DB and Tagging

IS_IN_DBバリデータは、multiple=Falseというオプション属性を持ちます。これがTrueに設定されている場合、複数の値が1つのフィールドに保存されます。このフィールドは、第6章で説明したlist:reference型にする必要があります。そこでは、明示的なタグ付けの例が説明されています。multipleの参照は作成と更新フォームにおいて自動的に処理されます。しかし、DALに対して透過的ではありません。multipleフィールドをレンダリングするためには、jQueryのmultiselectプラグインを使用することを強く勧めます。

The IS_IN_DB validator has an optional attribute multiple=False. If set to True multiple values can be stored in one field. This field should be of type list:reference as discussed in Chapter 6. An explicit example of tagging is discussed there. multiple references are handled automatically in create and update forms, but they are transparent to the DAL. We strongly suggest using the jQuery multiselect plugin to render multiple fields.

Custom Validators

すべてのバリデータは、以下のプロトタイプに従っています:

All validators follow the prototype below:

1.

2.

3.

4.

5.

6.

7.

8.

9.

10.

class sample_validator:

def __init__(self, *a, error_message='error'):

self.a = a

self.e = error_message

def __call__(self, value):

if validate(value):

return (parsed(value), None)

return (value, self.e)

def formatter(self, value):

return format(value)

すなわち、値を検証するために呼ばれたとき、バリデータは(x, y)というタプルを返します。yがNoneの場合、値は検証を通過し、xは通過した値を保持します。たとえば、バリデータが値に整数であることを要求する場合、xはint(value)に変換されます。値が検証を通過しない場合は、xは入力値を保持し、yは検証の失敗を説明するエラーメッセージを保持します。このエラーメッセージは、有効でないフォームにエラーを報告するために使用されます。

i.e., when called to validate a value, a validator returns a tuple (x, y). If y is None, then the value passed validation and x contains a parsed value. For example, if the validator requires the value to be an integer, x is converted to int(value). If the value did not pass validation, then x contains the input value and y contains an error message that explains the failed validation. This error message is used to report the error in forms that do not validate.

バリデータはformatterメソッドも持つことが可能です。これは、__call__が行うものと逆の変換を行う必要があります。たとえば、IS_DATEに対するソースコードを考えてみます:

The validator may also contain a formatter method. It must perform the opposite conversion to the one the __call__ does. For example, consider the source code for IS_DATE:

1.

2.

3.

4.

5.

6.

7.

8.

9.

10.

11.

12.

13.

class IS_DATE(object):

def __init__(self, format='%Y-%m-%d', error_message='must be YYYY-MM-DD!'):

self.format = format

self.error_message = error_message

def __call__(self, value):

try:

y, m, d, hh, mm, ss, t0, t1, t2 = time.strptime(value, str(self.format))

value = datetime.date(y, m, d)

return (value, None)

except:

return (value, self.error_message)

def formatter(self, value):

return value.strftime(str(self.format))

成功した場合、 __call__メソッドはフォームからデータ文字列を読み取り、コンストラクタで指定したフォーマット文字列を用いてそれをdatetime.dateオブジェクトに変換します。formatterオブジェクトは、datetime.dateオブジェクトを受け取り、同じフォーマットを用いてそれを文字列表現に変換します。formatterはフォームによって自動的に呼び出されます。しかし、明示的に使用して、オブジェクトを適切な表現に変換することもできます。例:

On success, the __call__ method reads a date string from the form and converts it into a datetime.date object using the format string specified in the constructor. The formatter object takes a datetime.date object and converts it to a string representation using the same format. The formatter is called automatically in forms, but you can also call it explicitly to convert objects into their proper representation. For example:

1.

2.

3.

4.

5.

6.

7.

>>> db = DAL()

>>> db.define_table('atable',

Field('birth', 'date', requires=IS_DATE('%m/%d/%Y')))

>>> id = db.atable.insert(birth=datetime.date(2008, 1, 1))

>>> row = db.atable[id]

>>> print db.atable.formatter(row.birth)

01/01/2008

複数のバリデータが要求(リストに格納)されたとき、それらは順序通りに実行され、1つの出力は入力として次のものへ渡されます。この連鎖は、バリデータのいずれかが失敗したときに中断されます。

When multiple validators are required (and stored in a list), they are executed in order and the output of one is passed as input to the next. The chain breaks when one of the validators fails.

反対に、フィールドのformatterメソッドを呼ぶとき、複数のバリデータに関連付けられたformattersもまた連鎖されますが、逆順になります。

Conversely, when we call the formatter method of a field, the formatters of the associated validators are also chained, but in reverse order.

依存関係をバリデータ

Validators with Dependencies

時折、フィールドを検証する必要があり、その検証が別のフィールドの値に依存することがあります。これは行うことができますが、バリデータの設定をコントローラで、他のフィールドの値を知ったときに、行う必要があります。例として、ユーザー名とパスワードを2回尋ねる登録フォームを生成するページを示します。どのフィールドも空にすることはできず、両者のパスワードは一致しなければなりません:

Occasionally, you need to validate a field and the validator depends on the value of another field. This can be done, but it requires setting the validator in the controller, when the value of the other field is known. For example, here is a page that generates a registration form that asks for username and password twice. None of the fields can be empty, and both passwords must match:

1.

2.

3.

4.

5.

6.

7.

8.

9.

def index():

form = SQLFORM.factory(

Field('username', requires=IS_NOT_EMPTY()),

Field('password', requires=IS_NOT_EMPTY()),

Field('password_again',

requires=IS_SAME_AS(request.vars.password)))

if form.accepts(request.vars, session):

pass # or take some action

return dict(form=form)

同じメカニズムは、FORMとSQLFORMオブジェクトに適用することができます。

The same mechanism can be applied to FORM and SQLFORM objects.