{"title":"フォームとフィールドの検証","version":"1.11","locale":"ja","docname":"ref/forms/validation","url":"/ja/1.11/ref/forms/validation/","canonical":"https://djangodocs.dev/ja/1.11/ref/forms/validation/","summary":"Form validation happens when the data is cleaned. If you want to customize this process, there are various places to make changes, each one serving a…","html":"<h1>フォームとフィールドの検証<a class=\"heading-anchor\" href=\"#form-and-field-validation\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h1>\n<p>Form validation happens when the data is cleaned. If you want to customize\nthis process, there are various places to make changes, each one serving a\ndifferent purpose. Three types of cleaning methods are run during form\nprocessing. These are normally executed when you call the <code class=\"docutils literal notranslate\">is_valid()</code>\nmethod on a form. There are other things that can also trigger cleaning and\nvalidation (accessing the <code class=\"docutils literal notranslate\">errors</code> attribute or calling <code class=\"docutils literal notranslate\">full_clean()</code>\ndirectly), but normally they won't be needed.</p>\n<p>In general, any cleaning method can raise <code class=\"docutils literal notranslate\">ValidationError</code> if there is a\nproblem with the data it is processing, passing the relevant information to\nthe <code class=\"docutils literal notranslate\">ValidationError</code> constructor. <a class=\"reference internal\" href=\"#raising-validation-error\"><span class=\"std std-ref\">See below</span></a>\nfor the best practice in raising <code class=\"docutils literal notranslate\">ValidationError</code>. If no <code class=\"docutils literal notranslate\">ValidationError</code>\nis raised, the method should return the cleaned (normalized) data as a Python\nobject.</p>\n<p>Most validation can be done using <a class=\"reference internal\" href=\"#validators\">validators</a> - simple helpers that can be\nreused easily. Validators are simple functions (or callables) that take a single\nargument and raise <code class=\"docutils literal notranslate\">ValidationError</code> on invalid input. Validators are run\nafter the field's <code class=\"docutils literal notranslate\">to_python</code> and <code class=\"docutils literal notranslate\">validate</code> methods have been called.</p>\n<p>Validation of a form is split into several steps, which can be customized or\noverridden:</p>\n<ul>\n<li><p>The <code class=\"docutils literal notranslate\">to_python()</code> method on a <code class=\"docutils literal notranslate\">Field</code> is the first step in every\nvalidation. It coerces the value to a correct datatype and raises\n<code class=\"docutils literal notranslate\">ValidationError</code> if that is not possible. This method accepts the raw\nvalue from the widget and returns the converted value. For example, a\n<code class=\"docutils literal notranslate\">FloatField</code> will turn the data into a Python <code class=\"docutils literal notranslate\">float</code> or raise a\n<code class=\"docutils literal notranslate\">ValidationError</code>.</p></li>\n<li><p>The <code class=\"docutils literal notranslate\">validate()</code> method on a <code class=\"docutils literal notranslate\">Field</code> handles field-specific validation\nthat is not suitable for a validator. It takes a value that has been\ncoerced to a correct datatype and raises <code class=\"docutils literal notranslate\">ValidationError</code> on any error.\nThis method does not return anything and shouldn't alter the value. You\nshould override it to handle validation logic that you can't or don't\nwant to put in a validator.</p></li>\n<li><p>The <code class=\"docutils literal notranslate\">run_validators()</code> method on a <code class=\"docutils literal notranslate\">Field</code> runs all of the field's\nvalidators and aggregates all the errors into a single\n<code class=\"docutils literal notranslate\">ValidationError</code>. You shouldn't need to override this method.</p></li>\n<li><p>The <code class=\"docutils literal notranslate\">clean()</code> method on a <code class=\"docutils literal notranslate\">Field</code> subclass is responsible for running\n<code class=\"docutils literal notranslate\">to_python()</code>, <code class=\"docutils literal notranslate\">validate()</code>, and <code class=\"docutils literal notranslate\">run_validators()</code> in the correct\norder and propagating their errors. If, at any time, any of the methods\nraise <code class=\"docutils literal notranslate\">ValidationError</code>, the validation stops and that error is raised.\nThis method returns the clean data, which is then inserted into the\n<code class=\"docutils literal notranslate\">cleaned_data</code> dictionary of the form.</p></li>\n<li><p>The <code class=\"docutils literal notranslate\">clean_&lt;fieldname&gt;()</code> method is called on a form subclass -- where\n<code class=\"docutils literal notranslate\">&lt;fieldname&gt;</code> is replaced with the name of the form field attribute.\nThis method does any cleaning that is specific to that particular\nattribute, unrelated to the type of field that it is. This method is not\npassed any parameters. You will need to look up the value of the field\nin <code class=\"docutils literal notranslate\">self.cleaned_data</code> and remember that it will be a Python object\nat this point, not the original string submitted in the form (it will be\nin <code class=\"docutils literal notranslate\">cleaned_data</code> because the general field <code class=\"docutils literal notranslate\">clean()</code> method, above,\nhas already cleaned the data once).</p>\n<p>For example, if you wanted to validate that the contents of a\n<code class=\"docutils literal notranslate\">CharField</code> called <code class=\"docutils literal notranslate\">serialnumber</code> was unique,\n<code class=\"docutils literal notranslate\">clean_serialnumber()</code> would be the right place to do this. You don't\nneed a specific field (it's just a <code class=\"docutils literal notranslate\">CharField</code>), but you want a\nformfield-specific piece of validation and, possibly,\ncleaning/normalizing the data.</p>\n<p>The return value of this method replaces the existing value in\n<code class=\"docutils literal notranslate\">cleaned_data</code>, so it must be the field's value from <code class=\"docutils literal notranslate\">cleaned_data</code> (even\nif this method didn't change it) or a new cleaned value.</p>\n</li>\n<li><p>The form subclass's <code class=\"docutils literal notranslate\">clean()</code> method can perform validation that requires\naccess to multiple form fields. This is where you might put in checks such as\n&quot;if field <code class=\"docutils literal notranslate\">A</code> is supplied, field <code class=\"docutils literal notranslate\">B</code> must contain a valid email address&quot;.\nThis method can return a completely different dictionary if it wishes, which\nwill be used as the <code class=\"docutils literal notranslate\">cleaned_data</code>.</p>\n<p>Since the field validation methods have been run by the time <code class=\"docutils literal notranslate\">clean()</code> is\ncalled, you also have access to the form's <code class=\"docutils literal notranslate\">errors</code> attribute which\ncontains all the errors raised by cleaning of individual fields.</p>\n<p>Note that any errors raised by your <a class=\"reference internal\" href=\"/ja/1.11/ref/forms/api/#django.forms.Form.clean\" title=\"django.forms.Form.clean\"><code class=\"xref py py-meth docutils literal notranslate\">Form.clean()</code></a> override will not\nbe associated with any field in particular. They go into a special\n&quot;field&quot; (called <code class=\"docutils literal notranslate\">__all__</code>), which you can access via the\n<a class=\"reference internal\" href=\"/ja/1.11/ref/forms/api/#django.forms.Form.non_field_errors\" title=\"django.forms.Form.non_field_errors\"><code class=\"xref py py-meth docutils literal notranslate\">non_field_errors()</code></a> method if you need to. If you\nwant to attach errors to a specific field in the form, you need to call\n<a class=\"reference internal\" href=\"/ja/1.11/ref/forms/api/#django.forms.Form.add_error\" title=\"django.forms.Form.add_error\"><code class=\"xref py py-meth docutils literal notranslate\">add_error()</code></a>.</p>\n<p>Also note that there are special considerations when overriding\nthe <code class=\"docutils literal notranslate\">clean()</code> method of a <code class=\"docutils literal notranslate\">ModelForm</code> subclass. (see the\n<a class=\"reference internal\" href=\"/ja/1.11/topics/forms/modelforms/#overriding-modelform-clean-method\"><span class=\"std std-ref\">ModelForm documentation</span></a> for more information)</p>\n</li>\n</ul>\n<p>These methods are run in the order given above, one field at a time.  That is,\nfor each field in the form (in the order they are declared in the form\ndefinition), the <code class=\"docutils literal notranslate\">Field.clean()</code> method (or its override) is run, then\n<code class=\"docutils literal notranslate\">clean_&lt;fieldname&gt;()</code>. Finally, once those two methods are run for every\nfield, the <a class=\"reference internal\" href=\"/ja/1.11/ref/forms/api/#django.forms.Form.clean\" title=\"django.forms.Form.clean\"><code class=\"xref py py-meth docutils literal notranslate\">Form.clean()</code></a> method, or its override, is executed whether\nor not the previous methods have raised errors.</p>\n<p>Examples of each of these methods are provided below.</p>\n<p>As mentioned, any of these methods can raise a <code class=\"docutils literal notranslate\">ValidationError</code>. For any\nfield, if the <code class=\"docutils literal notranslate\">Field.clean()</code> method raises a <code class=\"docutils literal notranslate\">ValidationError</code>, any\nfield-specific cleaning method is not called. However, the cleaning methods\nfor all remaining fields are still executed.</p>\n<section id=\"raising-validationerror\">\n<span id=\"raising-validation-error\"></span><h2><code class=\"docutils literal notranslate\">ValidationError</code> を発生させる<a class=\"heading-anchor\" href=\"#raising-validationerror\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>エラーメッセージを柔軟かつ簡単にオーバーライドできるようにするため、以下のガイドラインを検討してください:</p>\n<ul>\n<li><p>説明のための <code class=\"docutils literal notranslate\">code</code> をコンストラクタに渡します:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"c1\"># Good</span>\nValidationError<span class=\"p\">(</span>_<span class=\"p\">(</span><span class=\"s1\">&#39;Invalid value&#39;</span><span class=\"p\">),</span> code<span class=\"o\">=</span><span class=\"s1\">&#39;invalid&#39;</span><span class=\"p\">)</span>\n\n<span class=\"c1\"># Bad</span>\nValidationError<span class=\"p\">(</span>_<span class=\"p\">(</span><span class=\"s1\">&#39;Invalid value&#39;</span><span class=\"p\">))</span>\n</code></pre></div>\n</li>\n<li><p>メッセージには変数を強制しません; プレースホルダとコンストラクタの <code class=\"docutils literal notranslate\">params</code> 引数を使用します:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"c1\"># Good</span>\nValidationError<span class=\"p\">(</span>\n    _<span class=\"p\">(</span><span class=\"s1\">&#39;Invalid value: </span><span class=\"si\">%(value)s</span><span class=\"s1\">&#39;</span><span class=\"p\">),</span>\n    params<span class=\"o\">=</span><span class=\"p\">{</span><span class=\"s1\">&#39;value&#39;</span><span class=\"p\">:</span> <span class=\"s1\">&#39;42&#39;</span><span class=\"p\">},</span>\n<span class=\"p\">)</span>\n\n<span class=\"c1\"># Bad</span>\nValidationError<span class=\"p\">(</span>_<span class=\"p\">(</span><span class=\"s1\">&#39;Invalid value: </span><span class=\"si\">%s</span><span class=\"s1\">&#39;</span><span class=\"p\">)</span> <span class=\"o\">%</span> value<span class=\"p\">)</span>\n</code></pre></div>\n</li>\n<li><p>位置指定ではなく、マッピングキーを使います。</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"c1\"># Good</span>\nValidationError<span class=\"p\">(</span>\n    _<span class=\"p\">(</span><span class=\"s1\">&#39;Invalid value: </span><span class=\"si\">%(value)s</span><span class=\"s1\">&#39;</span><span class=\"p\">),</span>\n    params<span class=\"o\">=</span><span class=\"p\">{</span><span class=\"s1\">&#39;value&#39;</span><span class=\"p\">:</span> <span class=\"s1\">&#39;42&#39;</span><span class=\"p\">},</span>\n<span class=\"p\">)</span>\n\n<span class=\"c1\"># Bad</span>\nValidationError<span class=\"p\">(</span>\n    _<span class=\"p\">(</span><span class=\"s1\">&#39;Invalid value: </span><span class=\"si\">%s</span><span class=\"s1\">&#39;</span><span class=\"p\">),</span>\n    params<span class=\"o\">=</span><span class=\"p\">(</span><span class=\"s1\">&#39;42&#39;</span><span class=\"p\">,),</span>\n<span class=\"p\">)</span>\n</code></pre></div>\n</li>\n<li><p>メッセージを <code class=\"docutils literal notranslate\">gettext</code> でラップし、翻訳できるようにします:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"c1\"># Good</span>\nValidationError<span class=\"p\">(</span>_<span class=\"p\">(</span><span class=\"s1\">&#39;Invalid value&#39;</span><span class=\"p\">))</span>\n\n<span class=\"c1\"># Bad</span>\nValidationError<span class=\"p\">(</span><span class=\"s1\">&#39;Invalid value&#39;</span><span class=\"p\">)</span>\n</code></pre></div>\n</li>\n</ul>\n<p>全てを一緒に記述すると以下のようになります:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"k\">raise</span> ValidationError<span class=\"p\">(</span>\n    _<span class=\"p\">(</span><span class=\"s1\">&#39;Invalid value: </span><span class=\"si\">%(value)s</span><span class=\"s1\">&#39;</span><span class=\"p\">),</span>\n    code<span class=\"o\">=</span><span class=\"s1\">&#39;invalid&#39;</span><span class=\"p\">,</span>\n    params<span class=\"o\">=</span><span class=\"p\">{</span><span class=\"s1\">&#39;value&#39;</span><span class=\"p\">:</span> <span class=\"s1\">&#39;42&#39;</span><span class=\"p\">},</span>\n<span class=\"p\">)</span>\n</code></pre></div>\n<p>再利用可能なフォーム、フォームフィールド、モデルフィールドを記述した場合、特にこのガイドラインの遵守が必要となります。</p>\n<p>推奨はされませんが、バリデーションチェーンの最後で (例えばフォームの <code class=\"docutils literal notranslate\">clean()</code> メソッド) エラーメッセージのオーバーライドを <em>決してしない</em> ことが確かな場合は、より簡潔に記述することもできます:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code>ValidationError<span class=\"p\">(</span>_<span class=\"p\">(</span><span class=\"s1\">&#39;Invalid value: </span><span class=\"si\">%s</span><span class=\"s1\">&#39;</span><span class=\"p\">)</span> <span class=\"o\">%</span> value<span class=\"p\">)</span>\n</code></pre></div>\n<p>The <a class=\"reference internal\" href=\"/ja/1.11/ref/forms/api/#django.forms.Form.errors.as_data\" title=\"django.forms.Form.errors.as_data\"><code class=\"xref py py-meth docutils literal notranslate\">Form.errors.as_data()</code></a> and\n<a class=\"reference internal\" href=\"/ja/1.11/ref/forms/api/#django.forms.Form.errors.as_json\" title=\"django.forms.Form.errors.as_json\"><code class=\"xref py py-meth docutils literal notranslate\">Form.errors.as_json()</code></a> methods\ngreatly benefit from fully featured <code class=\"docutils literal notranslate\">ValidationError</code>s (with a <code class=\"docutils literal notranslate\">code</code> name\nand a <code class=\"docutils literal notranslate\">params</code> dictionary).</p>\n<section id=\"raising-multiple-errors\">\n<h3>複数のエラーを起こす<a class=\"heading-anchor\" href=\"#raising-multiple-errors\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>If you detect multiple errors during a cleaning method and wish to signal all\nof them to the form submitter, it is possible to pass a list of errors to the\n<code class=\"docutils literal notranslate\">ValidationError</code> constructor.</p>\n<p>As above, it is recommended to pass a list of <code class=\"docutils literal notranslate\">ValidationError</code> instances\nwith <code class=\"docutils literal notranslate\">code</code>s and <code class=\"docutils literal notranslate\">params</code> but a list of strings will also work:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"c1\"># Good</span>\n<span class=\"k\">raise</span> ValidationError<span class=\"p\">([</span>\n    ValidationError<span class=\"p\">(</span>_<span class=\"p\">(</span><span class=\"s1\">&#39;Error 1&#39;</span><span class=\"p\">),</span> code<span class=\"o\">=</span><span class=\"s1\">&#39;error1&#39;</span><span class=\"p\">),</span>\n    ValidationError<span class=\"p\">(</span>_<span class=\"p\">(</span><span class=\"s1\">&#39;Error 2&#39;</span><span class=\"p\">),</span> code<span class=\"o\">=</span><span class=\"s1\">&#39;error2&#39;</span><span class=\"p\">),</span>\n<span class=\"p\">])</span>\n\n<span class=\"c1\"># Bad</span>\n<span class=\"k\">raise</span> ValidationError<span class=\"p\">([</span>\n    _<span class=\"p\">(</span><span class=\"s1\">&#39;Error 1&#39;</span><span class=\"p\">),</span>\n    _<span class=\"p\">(</span><span class=\"s1\">&#39;Error 2&#39;</span><span class=\"p\">),</span>\n<span class=\"p\">])</span>\n</code></pre></div>\n</section>\n</section>\n<section id=\"using-validation-in-practice\">\n<h2>実際にバリデーションを使用する<a class=\"heading-anchor\" href=\"#using-validation-in-practice\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>前のセクションでは、フォームに対する検証が一般にどのように働くかを説明しました。実際の使われ方を見た方が機能をよく理解できるということが往々にしてあります。ここでは、説明した各機能を使った一連の小さな使用例を説明します。</p>\n<section id=\"using-validators\">\n<span id=\"validators\"></span><h3>バリデータを使う<a class=\"heading-anchor\" href=\"#using-validators\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>Django のフォーム (とモデル) フィールドは、バリデータと呼ばれるシンプルなユーティリティ関数とクラスの使用をサポートしています。バリデータは単純にカラブルオブジェクトか関数で、値を取って、値が有効な場合は何も返さず、無効な場合は exc:~django.core.exceptions.ValidationError を返します。フィールドの <code class=\"docutils literal notranslate\">validators</code> 引数を通してフィールドのコンストラクタに渡すことができます。もしくは、<a class=\"reference internal\" href=\"/ja/1.11/ref/forms/fields/#django.forms.Field\" title=\"django.forms.Field\"><code class=\"xref py py-class docutils literal notranslate\">Field</code></a> クラス自身で <code class=\"docutils literal notranslate\">default_validators</code> 属性を使って定義できます。</p>\n<p>シンプルなバリデータはフィールドの内部で値を検証賞するために使用できます。Django の <code class=\"docutils literal notranslate\">SlugField</code> を見てみましょう:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django.forms</span> <span class=\"kn\">import</span> CharField\n<span class=\"kn\">from</span> <span class=\"nn\">django.core</span> <span class=\"kn\">import</span> validators\n\n<span class=\"k\">class</span> <span class=\"nc\">SlugField</span><span class=\"p\">(</span>CharField<span class=\"p\">):</span>\n    default_validators <span class=\"o\">=</span> <span class=\"p\">[</span>validators<span class=\"o\">.</span>validate_slug<span class=\"p\">]</span>\n</code></pre></div>\n<p>見ての通り、<code class=\"docutils literal notranslate\">SlugField</code> はカスタマイズされたバリデータを伴う <code class=\"docutils literal notranslate\">CharField</code> で、このバリデータは送信されたテキストがいくつかの文字列ルールに従うかどうかを検証します。これはフィールド定義においても実装可能です:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code>slug <span class=\"o\">=</span> forms<span class=\"o\">.</span>SlugField<span class=\"p\">()</span>\n</code></pre></div>\n<p>これは以下と同じです:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code>slug <span class=\"o\">=</span> forms<span class=\"o\">.</span>CharField<span class=\"p\">(</span>validators<span class=\"o\">=</span><span class=\"p\">[</span>validators<span class=\"o\">.</span>validate_slug<span class=\"p\">])</span>\n</code></pre></div>\n<p>一般的なケース (例えば、E メールや正規表現に対する検証) は、Django が提供する既存のバリデータクラスを使って処理できます。例えば、<code class=\"docutils literal notranslate\">validators.validate_slug</code> は <a class=\"reference internal\" href=\"/ja/1.11/ref/validators/#django.core.validators.RegexValidator\" title=\"django.core.validators.RegexValidator\"><code class=\"xref py py-class docutils literal notranslate\">RegexValidator</code></a> の第 1 引数をパターン <code class=\"docutils literal notranslate\">^[-a-zA-Z0-9_]+$</code> としたインスタンスです。<a class=\"reference internal\" href=\"/ja/1.11/ref/validators/\"><span class=\"doc\">バリデータを記述する</span></a> のセクションを参照して、利用可能なバリデータのリストとバリデータの記述方法の例を確認できます。</p>\n</section>\n<section id=\"form-field-default-cleaning\">\n<h3>フォームフィールドのデフォルトのクリーニング<a class=\"heading-anchor\" href=\"#form-field-default-cleaning\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>Let's first create a custom form field that validates its input is a string\ncontaining comma-separated email addresses. The full class looks like this:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django</span> <span class=\"kn\">import</span> forms\n<span class=\"kn\">from</span> <span class=\"nn\">django.core.validators</span> <span class=\"kn\">import</span> validate_email\n\n<span class=\"k\">class</span> <span class=\"nc\">MultiEmailField</span><span class=\"p\">(</span>forms<span class=\"o\">.</span>Field<span class=\"p\">):</span>\n    <span class=\"k\">def</span> <span class=\"nf\">to_python</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> value<span class=\"p\">):</span>\n        <span class=\"sd\">&quot;&quot;&quot;Normalize data to a list of strings.&quot;&quot;&quot;</span>\n        <span class=\"c1\"># Return an empty list if no input was given.</span>\n        <span class=\"k\">if</span> <span class=\"ow\">not</span> value<span class=\"p\">:</span>\n            <span class=\"k\">return</span> <span class=\"p\">[]</span>\n        <span class=\"k\">return</span> value<span class=\"o\">.</span>split<span class=\"p\">(</span><span class=\"s1\">&#39;,&#39;</span><span class=\"p\">)</span>\n\n    <span class=\"k\">def</span> <span class=\"nf\">validate</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> value<span class=\"p\">):</span>\n        <span class=\"sd\">&quot;&quot;&quot;Check if value consists only of valid emails.&quot;&quot;&quot;</span>\n        <span class=\"c1\"># Use the parent&#39;s handling of required fields, etc.</span>\n        <span class=\"nb\">super</span><span class=\"p\">(</span>MultiEmailField<span class=\"p\">,</span> <span class=\"bp\">self</span><span class=\"p\">)</span><span class=\"o\">.</span>validate<span class=\"p\">(</span>value<span class=\"p\">)</span>\n        <span class=\"k\">for</span> email <span class=\"ow\">in</span> value<span class=\"p\">:</span>\n            validate_email<span class=\"p\">(</span>email<span class=\"p\">)</span>\n</code></pre></div>\n<p>Every form that uses this field will have these methods run before anything\nelse can be done with the field's data. This is cleaning that is specific to\nthis type of field, regardless of how it is subsequently used.</p>\n<p>Let's create a simple <code class=\"docutils literal notranslate\">ContactForm</code> to demonstrate how you'd use this\nfield:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"k\">class</span> <span class=\"nc\">ContactForm</span><span class=\"p\">(</span>forms<span class=\"o\">.</span>Form<span class=\"p\">):</span>\n    subject <span class=\"o\">=</span> forms<span class=\"o\">.</span>CharField<span class=\"p\">(</span>max_length<span class=\"o\">=</span><span class=\"mi\">100</span><span class=\"p\">)</span>\n    message <span class=\"o\">=</span> forms<span class=\"o\">.</span>CharField<span class=\"p\">()</span>\n    sender <span class=\"o\">=</span> forms<span class=\"o\">.</span>EmailField<span class=\"p\">()</span>\n    recipients <span class=\"o\">=</span> MultiEmailField<span class=\"p\">()</span>\n    cc_myself <span class=\"o\">=</span> forms<span class=\"o\">.</span>BooleanField<span class=\"p\">(</span>required<span class=\"o\">=</span><span class=\"kc\">False</span><span class=\"p\">)</span>\n</code></pre></div>\n<p>Simply use <code class=\"docutils literal notranslate\">MultiEmailField</code> like any other form field. When the\n<code class=\"docutils literal notranslate\">is_valid()</code> method is called on the form, the <code class=\"docutils literal notranslate\">MultiEmailField.clean()</code>\nmethod will be run as part of the cleaning process and it will, in turn, call\nthe custom <code class=\"docutils literal notranslate\">to_python()</code> and <code class=\"docutils literal notranslate\">validate()</code> methods.</p>\n</section>\n<section id=\"cleaning-a-specific-field-attribute\">\n<h3>特定のフィールド属性をクリーニングする<a class=\"heading-anchor\" href=\"#cleaning-a-specific-field-attribute\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>Continuing on from the previous example, suppose that in our <code class=\"docutils literal notranslate\">ContactForm</code>,\nwe want to make sure that the <code class=\"docutils literal notranslate\">recipients</code> field always contains the address\n<code class=\"docutils literal notranslate\">&quot;fred&#64;example.com&quot;</code>. This is validation that is specific to our form, so we\ndon't want to put it into the general <code class=\"docutils literal notranslate\">MultiEmailField</code> class. Instead, we\nwrite a cleaning method that operates on the <code class=\"docutils literal notranslate\">recipients</code> field, like so:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django</span> <span class=\"kn\">import</span> forms\n\n<span class=\"k\">class</span> <span class=\"nc\">ContactForm</span><span class=\"p\">(</span>forms<span class=\"o\">.</span>Form<span class=\"p\">):</span>\n    <span class=\"c1\"># Everything as before.</span>\n    <span class=\"o\">...</span>\n\n    <span class=\"k\">def</span> <span class=\"nf\">clean_recipients</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n        data <span class=\"o\">=</span> <span class=\"bp\">self</span><span class=\"o\">.</span>cleaned_data<span class=\"p\">[</span><span class=\"s1\">&#39;recipients&#39;</span><span class=\"p\">]</span>\n        <span class=\"k\">if</span> <span class=\"s2\">&quot;fred@example.com&quot;</span> <span class=\"ow\">not</span> <span class=\"ow\">in</span> data<span class=\"p\">:</span>\n            <span class=\"k\">raise</span> forms<span class=\"o\">.</span>ValidationError<span class=\"p\">(</span><span class=\"s2\">&quot;You have forgotten about Fred!&quot;</span><span class=\"p\">)</span>\n\n        <span class=\"c1\"># Always return a value to use as the new cleaned data, even if</span>\n        <span class=\"c1\"># this method didn&#39;t change it.</span>\n        <span class=\"k\">return</span> data\n</code></pre></div>\n</section>\n<section id=\"cleaning-and-validating-fields-that-depend-on-each-other\">\n<span id=\"validating-fields-with-clean\"></span><h3>互いに依存するフィールドをクリーニングして検証する<a class=\"heading-anchor\" href=\"#cleaning-and-validating-fields-that-depend-on-each-other\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>Suppose we add another requirement to our contact form: if the <code class=\"docutils literal notranslate\">cc_myself</code>\nfield is <code class=\"docutils literal notranslate\">True</code>, the <code class=\"docutils literal notranslate\">subject</code> must contain the word <code class=\"docutils literal notranslate\">&quot;help&quot;</code>. We are\nperforming validation on more than one field at a time, so the form's\n<a class=\"reference internal\" href=\"/ja/1.11/ref/forms/api/#django.forms.Form.clean\" title=\"django.forms.Form.clean\"><code class=\"xref py py-meth docutils literal notranslate\">clean()</code></a> method is a good spot to do this. Notice that we are\ntalking about the <code class=\"docutils literal notranslate\">clean()</code> method on the form here, whereas earlier we were\nwriting a <code class=\"docutils literal notranslate\">clean()</code> method on a field. It's important to keep the field and\nform difference clear when working out where to validate things. Fields are\nsingle data points, forms are a collection of fields.</p>\n<p>By the time the form's <code class=\"docutils literal notranslate\">clean()</code> method is called, all the individual field\nclean methods will have been run (the previous two sections), so\n<code class=\"docutils literal notranslate\">self.cleaned_data</code> will be populated with any data that has survived so\nfar. So you also need to remember to allow for the fact that the fields you\nare wanting to validate might not have survived the initial individual field\nchecks.</p>\n<p>There are two ways to report any errors from this step. Probably the most\ncommon method is to display the error at the top of the form. To create such\nan error, you can raise a <code class=\"docutils literal notranslate\">ValidationError</code> from the <code class=\"docutils literal notranslate\">clean()</code> method. For\nexample:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django</span> <span class=\"kn\">import</span> forms\n\n<span class=\"k\">class</span> <span class=\"nc\">ContactForm</span><span class=\"p\">(</span>forms<span class=\"o\">.</span>Form<span class=\"p\">):</span>\n    <span class=\"c1\"># Everything as before.</span>\n    <span class=\"o\">...</span>\n\n    <span class=\"k\">def</span> <span class=\"nf\">clean</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n        cleaned_data <span class=\"o\">=</span> <span class=\"nb\">super</span><span class=\"p\">(</span>ContactForm<span class=\"p\">,</span> <span class=\"bp\">self</span><span class=\"p\">)</span><span class=\"o\">.</span>clean<span class=\"p\">()</span>\n        cc_myself <span class=\"o\">=</span> cleaned_data<span class=\"o\">.</span>get<span class=\"p\">(</span><span class=\"s2\">&quot;cc_myself&quot;</span><span class=\"p\">)</span>\n        subject <span class=\"o\">=</span> cleaned_data<span class=\"o\">.</span>get<span class=\"p\">(</span><span class=\"s2\">&quot;subject&quot;</span><span class=\"p\">)</span>\n\n        <span class=\"k\">if</span> cc_myself <span class=\"ow\">and</span> subject<span class=\"p\">:</span>\n            <span class=\"c1\"># Only do something if both fields are valid so far.</span>\n            <span class=\"k\">if</span> <span class=\"s2\">&quot;help&quot;</span> <span class=\"ow\">not</span> <span class=\"ow\">in</span> subject<span class=\"p\">:</span>\n                <span class=\"k\">raise</span> forms<span class=\"o\">.</span>ValidationError<span class=\"p\">(</span>\n                    <span class=\"s2\">&quot;Did not send for &#39;help&#39; in the subject despite &quot;</span>\n                    <span class=\"s2\">&quot;CC&#39;ing yourself.&quot;</span>\n                <span class=\"p\">)</span>\n</code></pre></div>\n<p>In this code, if the validation error is raised, the form will display an\nerror message at the top of the form (normally) describing the problem.</p>\n<p>The call to <code class=\"docutils literal notranslate\">super(ContactForm, self).clean()</code> in the example code ensures\nthat any validation logic in parent classes is maintained. If your form\ninherits another that doesn't return a <code class=\"docutils literal notranslate\">cleaned_data</code> dictionary in its\n<code class=\"docutils literal notranslate\">clean()</code> method (doing so is optional), then don't assign <code class=\"docutils literal notranslate\">cleaned_data</code>\nto the result of the <code class=\"docutils literal notranslate\">super()</code> call and use <code class=\"docutils literal notranslate\">self.cleaned_data</code> instead:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"k\">def</span> <span class=\"nf\">clean</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n    <span class=\"nb\">super</span><span class=\"p\">(</span>ContactForm<span class=\"p\">,</span> <span class=\"bp\">self</span><span class=\"p\">)</span><span class=\"o\">.</span>clean<span class=\"p\">()</span>\n    cc_myself <span class=\"o\">=</span> <span class=\"bp\">self</span><span class=\"o\">.</span>cleaned_data<span class=\"o\">.</span>get<span class=\"p\">(</span><span class=\"s2\">&quot;cc_myself&quot;</span><span class=\"p\">)</span>\n    <span class=\"o\">...</span>\n</code></pre></div>\n<p>The second approach for reporting validation errors might involve assigning the\nerror message to one of the fields. In this case, let's assign an error message\nto both the &quot;subject&quot; and &quot;cc_myself&quot; rows in the form display. Be careful when\ndoing this in practice, since it can lead to confusing form output. We're\nshowing what is possible here and leaving it up to you and your designers to\nwork out what works effectively in your particular situation. Our new code\n(replacing the previous sample) looks like this:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django</span> <span class=\"kn\">import</span> forms\n\n<span class=\"k\">class</span> <span class=\"nc\">ContactForm</span><span class=\"p\">(</span>forms<span class=\"o\">.</span>Form<span class=\"p\">):</span>\n    <span class=\"c1\"># Everything as before.</span>\n    <span class=\"o\">...</span>\n\n    <span class=\"k\">def</span> <span class=\"nf\">clean</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n        cleaned_data <span class=\"o\">=</span> <span class=\"nb\">super</span><span class=\"p\">(</span>ContactForm<span class=\"p\">,</span> <span class=\"bp\">self</span><span class=\"p\">)</span><span class=\"o\">.</span>clean<span class=\"p\">()</span>\n        cc_myself <span class=\"o\">=</span> cleaned_data<span class=\"o\">.</span>get<span class=\"p\">(</span><span class=\"s2\">&quot;cc_myself&quot;</span><span class=\"p\">)</span>\n        subject <span class=\"o\">=</span> cleaned_data<span class=\"o\">.</span>get<span class=\"p\">(</span><span class=\"s2\">&quot;subject&quot;</span><span class=\"p\">)</span>\n\n        <span class=\"k\">if</span> cc_myself <span class=\"ow\">and</span> subject <span class=\"ow\">and</span> <span class=\"s2\">&quot;help&quot;</span> <span class=\"ow\">not</span> <span class=\"ow\">in</span> subject<span class=\"p\">:</span>\n            msg <span class=\"o\">=</span> <span class=\"s2\">&quot;Must put &#39;help&#39; in subject when cc&#39;ing yourself.&quot;</span>\n            <span class=\"bp\">self</span><span class=\"o\">.</span>add_error<span class=\"p\">(</span><span class=\"s1\">&#39;cc_myself&#39;</span><span class=\"p\">,</span> msg<span class=\"p\">)</span>\n            <span class=\"bp\">self</span><span class=\"o\">.</span>add_error<span class=\"p\">(</span><span class=\"s1\">&#39;subject&#39;</span><span class=\"p\">,</span> msg<span class=\"p\">)</span>\n</code></pre></div>\n<p>The second argument of <code class=\"docutils literal notranslate\">add_error()</code> can be a simple string, or preferably\nan instance of <code class=\"docutils literal notranslate\">ValidationError</code>. See <a class=\"reference internal\" href=\"#raising-validation-error\"><span class=\"std std-ref\">ValidationError を発生させる</span></a> for\nmore details. Note that <code class=\"docutils literal notranslate\">add_error()</code> automatically removes the field\nfrom <code class=\"docutils literal notranslate\">cleaned_data</code>.</p>\n</section>\n</section>","rootId":"form-and-field-validation","toc":[{"title":"ValidationError を発生させる","anchor":"raising-validationerror","children":[{"title":"複数のエラーを起こす","anchor":"raising-multiple-errors","children":[]}]},{"title":"実際にバリデーションを使用する","anchor":"using-validation-in-practice","children":[{"title":"バリデータを使う","anchor":"using-validators","children":[]},{"title":"フォームフィールドのデフォルトのクリーニング","anchor":"form-field-default-cleaning","children":[]},{"title":"特定のフィールド属性をクリーニングする","anchor":"cleaning-a-specific-field-attribute","children":[]},{"title":"互いに依存するフィールドをクリーニングして検証する","anchor":"cleaning-and-validating-fields-that-depend-on-each-other","children":[]}]}],"breadcrumbs":[{"docname":"ref/index","title":"API Reference","url":"/ja/1.11/ref/"},{"docname":"ref/forms/index","title":"フォーム","url":"/ja/1.11/ref/forms/"}],"prev":{"docname":"ref/forms/widgets","title":"ウィジェット","url":"/ja/1.11/ref/forms/widgets/"},"next":{"docname":"ref/middleware","title":"ミドルウェア","url":"/ja/1.11/ref/middleware/"},"formats":{"html":"/ja/1.11/ref/forms/validation/","markdown":"/ja/1.11/ref/forms/validation.md","json":"/ja/1.11/ref/forms/validation.json"},"source":"https://github.com/django/django/blob/stable/1.11.x/docs/ref/forms/validation.txt","official":"https://docs.djangoproject.com/ja/1.11/ref/forms/validation/","inVersions":["6.1","6.0","5.2","5.1","5.0","4.2","4.1","4.0","3.2","3.1","3.0","2.2","2.1","2.0","1.11","1.10","1.9"],"inLocales":["en","fr","ja","id","pt-br","ko","es","el","pl"]}