---
title: "フォームとフィールドの検証"
version: 2.0
locale: ja
source: https://docs.djangoproject.com/ja/2.0/ref/forms/validation/
canonical: https://djangodocs.dev/ja/2.0/ref/forms/validation/
---
# フォームとフィールドの検証

フォームのバリデーションは、データがクリーニング (clean) されるときに実行されます。このプロセスをカスタムしたい場合は、様々な箇所に変更を加えることができ、それぞれが違う目的を持っています。クリーニング方法のうち 3 タイプは、フォームのプロセス中に実行されます。これらは、通常フォーム上の `is_valid()` メソッドを呼び出したときに実行されます。このほかにも、クリーニングとバリデーションのトリガーとなる処理 (直接 `errors` 属性にアクセスしたり、 `full_clean()` を直接呼び出す) がありますが、通常必要とはなりません。

一般的に、あらゆるクリーニング方法は `ValidationError` を投げる可能性があります。処理されるデータに問題がある場合、関連情報を `ValidationError` コンストラクタに渡します。[下記項目](#raising-validation-error) に、`ValidationError` を投げる際のベストプラクティスがあります。`ValidationError` が投げられない場合、メソッドはクリーニングされた (標準化された) データを Python オブジェクトとして返すはずです。

大半のバリデーションは、[validators](#validators) を使って行うことができます- シンプルなヘルパーで、再利用も簡単です。バリデータはシンプルな関数 (ないしカラブル) で、単一の引数を取り無効な入力において `ValidationError` を投げます。 バリデータは、フィールド `to_python` と `validate` メソッドが呼び出された後に実行されます。

フォームのバリデーションは複数のステップに分割されます。カスタムやオーバーライドすることができます:

- `Field` の `to_python()` メソッドはすべてのバリデーションの最初のステップとなります。これは、値をデータ型に正すことを強制し、それができない場合は `ValidationError` を投げます。このメソッドはウィジェットからそのままの値を受け取り、変換した値を返します。たとえば、`FloatField` は Python の `float` に変換されるか、もしくは `ValidationError` を投げます。
- `Field` の `validate()` メソッドは、フィールド特有のバリデーションを行います。これはバリデータとしては不適です。正しいデータ型を強制された値を取り、エラーの際は `ValidationError` を投げます。このメソッドは何も返さず、また値の変更も行わないはずです。バリデータに記述したくないバリデーションロジックを実行するためには、このメソッドをオーバーライドしてください。
- `Field` の `run_validators()` メソッドはフィールドのバリデータをすべて実行し、すべてのエラーを単一の `ValidationError` に統合します。このメソッドをオーバーライドする必要はないはずです。
- `Field` サブクラスの `clean()` メソッドは、`to_python()`、`validate()`、`run_validators()` を正しい順序で実行し、エラーを伝達する役目を負っています。もしこの過程のどこかで `ValidationError` が投げられた場合、バリデーションは停止し、そのエラーを投げます。このメソッドはクリーニングされたデータを返し、フォームの `cleaned_data` ディクショナリに格納します。
- `clean_<fieldname>()` メソッドは、フォームサブクラス上で呼び出されます -- `<fieldname>` がフォームのフィールド属性の名前と置き換えられます。このメソッドは、フィールドのタイプにかかわらず、その特定の属性に対するクリーニングを実行します。 このメソッドはパラメータを受け取りません。`self.cleaned_data` 内のフィールドの値を検索する必要があり、またこの時点ではフォーム上で元々送信された文字列ではなく Python オブジェクトであること覚えておいてください (これは `cleaned_data` 内にあります。上記に出てきた一般フィールドの `clean()` メソッドがすでに一度データをクリーニングしているからです)。

  たとえば、 `serialnumber` と呼ばれる `CharField` の内容がユニークであることをバリデートしたいとき、 `clean_serialnumber()` が最も適切な場所となり得ます。 特定のフィールド (この場合 `CharField`) は必要ありませんが、フォームのフィールドに紐付いたバリデーションと、おそらくデータのクリーニングおよび標準化も必要となるでしょう。

  このメソッドの戻り値は `cleaned_data` 内の既存の値を置き換えるため、(たとえこのメソッドが変更しなかったとしても) `cleaned_data` からのフィールドの値か、新しくクリーニングされた値になるはずです。
- The form subclass's `clean()` method can perform validation that requires
  access to multiple form fields. This is where you might put in checks such as
  "if field `A` is supplied, field `B` must contain a valid email address".
  This method can return a completely different dictionary if it wishes, which
  will be used as the `cleaned_data`.

  Since the field validation methods have been run by the time `clean()` is
  called, you also have access to the form's `errors` attribute which
  contains all the errors raised by cleaning of individual fields.

  Note that any errors raised by your [`Form.clean()`](/ja/2.0/ref/forms/api/#django.forms.Form.clean) override will not
  be associated with any field in particular. They go into a special
  "field" (called `__all__`), which you can access via the
  [`non_field_errors()`](/ja/2.0/ref/forms/api/#django.forms.Form.non_field_errors) method if you need to. If you
  want to attach errors to a specific field in the form, you need to call
  [`add_error()`](/ja/2.0/ref/forms/api/#django.forms.Form.add_error).

  Also note that there are special considerations when overriding
  the `clean()` method of a `ModelForm` subclass. (see the
  [ModelForm documentation](/ja/2.0/topics/forms/modelforms/#overriding-modelform-clean-method) for more information)

These methods are run in the order given above, one field at a time.  That is,
for each field in the form (in the order they are declared in the form
definition), the `Field.clean()` method (or its override) is run, then
`clean_<fieldname>()`. Finally, once those two methods are run for every
field, the [`Form.clean()`](/ja/2.0/ref/forms/api/#django.forms.Form.clean) method, or its override, is executed whether
or not the previous methods have raised errors.

Examples of each of these methods are provided below.

As mentioned, any of these methods can raise a `ValidationError`. For any
field, if the `Field.clean()` method raises a `ValidationError`, any
field-specific cleaning method is not called. However, the cleaning methods
for all remaining fields are still executed.

## `ValidationError` を発生させる

エラーメッセージを柔軟かつ簡単にオーバーライドできるようにするため、以下のガイドラインを検討してください:

- 説明のための `code` をコンストラクタに渡します:

  ```
  # Good
  ValidationError(_('Invalid value'), code='invalid')

  # Bad
  ValidationError(_('Invalid value'))
  ```
- メッセージには変数を強制しません; プレースホルダとコンストラクタの `params` 引数を使用します:

  ```
  # Good
  ValidationError(
      _('Invalid value: %(value)s'),
      params={'value': '42'},
  )

  # Bad
  ValidationError(_('Invalid value: %s') % value)
  ```
- 位置指定ではなく、マッピングキーを使います。

  ```
  # Good
  ValidationError(
      _('Invalid value: %(value)s'),
      params={'value': '42'},
  )

  # Bad
  ValidationError(
      _('Invalid value: %s'),
      params=('42',),
  )
  ```
- メッセージを `gettext` でラップし、翻訳できるようにします:

  ```
  # Good
  ValidationError(_('Invalid value'))

  # Bad
  ValidationError('Invalid value')
  ```

全てを一緒に記述すると以下のようになります:

```
raise ValidationError(
    _('Invalid value: %(value)s'),
    code='invalid',
    params={'value': '42'},
)
```

再利用可能なフォーム、フォームフィールド、モデルフィールドを記述した場合、特にこのガイドラインの遵守が必要となります。

推奨はされませんが、バリデーションチェーンの最後で (例えばフォームの `clean()` メソッド) エラーメッセージのオーバーライドを *決してしない* ことが確かな場合は、より簡潔に記述することもできます:

```
ValidationError(_('Invalid value: %s') % value)
```

The [`Form.errors.as_data()`](/ja/2.0/ref/forms/api/#django.forms.Form.errors.as_data) and
[`Form.errors.as_json()`](/ja/2.0/ref/forms/api/#django.forms.Form.errors.as_json) methods
greatly benefit from fully featured `ValidationError`s (with a `code` name
and a `params` dictionary).

### 複数のエラーを起こす

If you detect multiple errors during a cleaning method and wish to signal all
of them to the form submitter, it is possible to pass a list of errors to the
`ValidationError` constructor.

As above, it is recommended to pass a list of `ValidationError` instances
with `code`s and `params` but a list of strings will also work:

```
# Good
raise ValidationError([
    ValidationError(_('Error 1'), code='error1'),
    ValidationError(_('Error 2'), code='error2'),
])

# Bad
raise ValidationError([
    _('Error 1'),
    _('Error 2'),
])
```

## 実際にバリデーションを使用する

前のセクションでは、フォームに対する検証が一般にどのように働くかを説明しました。実際の使われ方を見た方が機能をよく理解できるということが往々にしてあります。ここでは、説明した各機能を使った一連の小さな使用例を説明します。

### バリデータを使う

Django のフォーム (とモデル) フィールドは、バリデータと呼ばれるシンプルなユーティリティ関数とクラスの使用をサポートしています。バリデータは単純にカラブルオブジェクトか関数で、値を取って、値が有効な場合は何も返さず、無効な場合は exc:~django.core.exceptions.ValidationError を返します。フィールドの `validators` 引数を通してフィールドのコンストラクタに渡すことができます。もしくは、[`Field`](/ja/2.0/ref/forms/fields/#django.forms.Field) クラス自身で `default_validators` 属性を使って定義できます。

シンプルなバリデータはフィールドの内部で値を検証賞するために使用できます。Django の `SlugField` を見てみましょう:

```
from django.core import validators
from django.forms import CharField

class SlugField(CharField):
    default_validators = [validators.validate_slug]
```

見ての通り、`SlugField` はカスタマイズされたバリデータを伴う `CharField` で、このバリデータは送信されたテキストがいくつかの文字列ルールに従うかどうかを検証します。これはフィールド定義においても実装可能です:

```
slug = forms.SlugField()
```

これは以下と同じです:

```
slug = forms.CharField(validators=[validators.validate_slug])
```

一般的なケース (例えば、E メールや正規表現に対する検証) は、Django が提供する既存のバリデータクラスを使って処理できます。例えば、`validators.validate_slug` は [`RegexValidator`](/ja/2.0/ref/validators/#django.core.validators.RegexValidator) の第 1 引数をパターン `^[-a-zA-Z0-9_]+$` としたインスタンスです。[バリデータを記述する](/ja/2.0/ref/validators/) のセクションを参照して、利用可能なバリデータのリストとバリデータの記述方法の例を確認できます。

### フォームフィールドのデフォルトのクリーニング

Let's first create a custom form field that validates its input is a string
containing comma-separated email addresses. The full class looks like this:

```
from django import forms
from django.core.validators import validate_email

class MultiEmailField(forms.Field):
    def to_python(self, value):
        """Normalize data to a list of strings."""
        # Return an empty list if no input was given.
        if not value:
            return []
        return value.split(',')

    def validate(self, value):
        """Check if value consists only of valid emails."""
        # Use the parent's handling of required fields, etc.
        super().validate(value)
        for email in value:
            validate_email(email)
```

Every form that uses this field will have these methods run before anything
else can be done with the field's data. This is cleaning that is specific to
this type of field, regardless of how it is subsequently used.

Let's create a simple `ContactForm` to demonstrate how you'd use this
field:

```
class ContactForm(forms.Form):
    subject = forms.CharField(max_length=100)
    message = forms.CharField()
    sender = forms.EmailField()
    recipients = MultiEmailField()
    cc_myself = forms.BooleanField(required=False)
```

Simply use `MultiEmailField` like any other form field. When the
`is_valid()` method is called on the form, the `MultiEmailField.clean()`
method will be run as part of the cleaning process and it will, in turn, call
the custom `to_python()` and `validate()` methods.

### 特定のフィールド属性をクリーニングする

Continuing on from the previous example, suppose that in our `ContactForm`,
we want to make sure that the `recipients` field always contains the address
`"fred@example.com"`. This is validation that is specific to our form, so we
don't want to put it into the general `MultiEmailField` class. Instead, we
write a cleaning method that operates on the `recipients` field, like so:

```
from django import forms

class ContactForm(forms.Form):
    # Everything as before.
    ...

    def clean_recipients(self):
        data = self.cleaned_data['recipients']
        if "fred@example.com" not in data:
            raise forms.ValidationError("You have forgotten about Fred!")

        # Always return a value to use as the new cleaned data, even if
        # this method didn't change it.
        return data
```

### 互いに依存するフィールドをクリーニングして検証する

Suppose we add another requirement to our contact form: if the `cc_myself`
field is `True`, the `subject` must contain the word `"help"`. We are
performing validation on more than one field at a time, so the form's
[`clean()`](/ja/2.0/ref/forms/api/#django.forms.Form.clean) method is a good spot to do this. Notice that we are
talking about the `clean()` method on the form here, whereas earlier we were
writing a `clean()` method on a field. It's important to keep the field and
form difference clear when working out where to validate things. Fields are
single data points, forms are a collection of fields.

By the time the form's `clean()` method is called, all the individual field
clean methods will have been run (the previous two sections), so
`self.cleaned_data` will be populated with any data that has survived so
far. So you also need to remember to allow for the fact that the fields you
are wanting to validate might not have survived the initial individual field
checks.

There are two ways to report any errors from this step. Probably the most
common method is to display the error at the top of the form. To create such
an error, you can raise a `ValidationError` from the `clean()` method. For
example:

```
from django import forms

class ContactForm(forms.Form):
    # Everything as before.
    ...

    def clean(self):
        cleaned_data = super().clean()
        cc_myself = cleaned_data.get("cc_myself")
        subject = cleaned_data.get("subject")

        if cc_myself and subject:
            # Only do something if both fields are valid so far.
            if "help" not in subject:
                raise forms.ValidationError(
                    "Did not send for 'help' in the subject despite "
                    "CC'ing yourself."
                )
```

In this code, if the validation error is raised, the form will display an
error message at the top of the form (normally) describing the problem.

The call to `super().clean()` in the example code ensures that any validation
logic in parent classes is maintained. If your form inherits another that
doesn't return a `cleaned_data` dictionary in its `clean()` method (doing
so is optional), then don't assign `cleaned_data` to the result of the
`super()` call and use `self.cleaned_data` instead:

```
def clean(self):
    super().clean()
    cc_myself = self.cleaned_data.get("cc_myself")
    ...
```

The second approach for reporting validation errors might involve assigning the
error message to one of the fields. In this case, let's assign an error message
to both the "subject" and "cc\_myself" rows in the form display. Be careful when
doing this in practice, since it can lead to confusing form output. We're
showing what is possible here and leaving it up to you and your designers to
work out what works effectively in your particular situation. Our new code
(replacing the previous sample) looks like this:

```
from django import forms

class ContactForm(forms.Form):
    # Everything as before.
    ...

    def clean(self):
        cleaned_data = super().clean()
        cc_myself = cleaned_data.get("cc_myself")
        subject = cleaned_data.get("subject")

        if cc_myself and subject and "help" not in subject:
            msg = "Must put 'help' in subject when cc'ing yourself."
            self.add_error('cc_myself', msg)
            self.add_error('subject', msg)
```

The second argument of `add_error()` can be a simple string, or preferably
an instance of `ValidationError`. See [ValidationError を発生させる](#raising-validation-error) for
more details. Note that `add_error()` automatically removes the field
from `cleaned_data`.
