{"title":"Pengesahan formulir dan bidang","version":"5.0","locale":"id","docname":"ref/forms/validation","url":"/id/5.0/ref/forms/validation/","canonical":"https://djangodocs.dev/id/5.0/ref/forms/validation/","summary":"Pengesahan formulir terjadi ketika data dibersihkan. Jika anda ingin menyesuaikan pengolahan ini, ada beragam tempat untuk membuat perubahan, setiap satu…","html":"<h1>Pengesahan formulir dan bidang<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>Pengesahan formulir terjadi ketika data dibersihkan. Jika anda ingin menyesuaikan pengolahan ini, ada beragam tempat untuk membuat perubahan, setiap satu melayani tujuan berbeda. Tiga jenis dari metode membersihkan berjalan selama pengolahan formulir. Ini biasanya dijalankan ketika anda memanggil metode <code class=\"docutils literal notranslate\">is_valid()</code> pada sebuah formulir. Ada hal-hal lain yang dapat juga memicu membersihkan dan pengesahan (mengakses atribut <code class=\"docutils literal notranslate\">errors</code> atau memanggil <code class=\"docutils literal notranslate\">full_clean()</code> langsung), tetapi biasanya mereka tidak akan dibutuhkan.</p>\n<p>Secara umum, metode pembersihan apapun dapat memunculkan <code class=\"docutils literal notranslate\">ValidationError</code> jika ada sebuah masalah dengan data itu sedang olah, melewatkan informasi bersangkut pautke pembangun <code class=\"docutils literal notranslate\">ValidationError</code>. <a class=\"reference internal\" href=\"#raising-validation-error\"><span class=\"std std-ref\">See below</span></a> untuk latihan terbaik dalam memunculkan <code class=\"docutils literal notranslate\">ValidationError</code>. Jika tidak <code class=\"docutils literal notranslate\">ValidationError</code> dimunculkan, metode harus mengembalikan data  dibersihkan (dinormalkan) sebagai sebuah obyek Python.</p>\n<p>Most validation can be done using <a class=\"reference internal\" href=\"#validators\">validators</a> - helpers that can be reused.\nValidators are functions (or callables) that take a single argument and raise\n<code class=\"docutils literal notranslate\">ValidationError</code> on invalid input. Validators are run after the field's\n<code class=\"docutils literal notranslate\">to_python</code> and <code class=\"docutils literal notranslate\">validate</code> methods have been called.</p>\n<p>Pengesahan dari sebuah formulir dibagi menjadi beberapa langkah, yang dapat disesuaikan atau ditimpa:</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>Metode clean_&lt;fieldname&gt;()` dipanggil di sebuah formulir subkelas -- dimana <code class=\"docutils literal notranslate\">&lt;fieldname&gt;</code> diganti dengan nama dari atribut bidang formulir. Metode ini melakukan pembersihan apapun yaitu khusus pada atribut tertentu, tidak terkait pada jenis dari bidang bahwa itu adalah. Metode ini tidak melewatkan parameter apapun. Anda akan butuh mencari nilai dari bidang di <code class=\"docutils literal notranslate\">self.cleaned_data</code> dan mengingat bahwa itu akan menjadi obyek Python pada titik ini, bukan string asli yang diajukan di formulir (itu akan di <code class=\"docutils literal notranslate\">cleaned_data</code> karena metode <code class=\"docutils literal notranslate\">clean()</code> bidang umum, diatas, telah membersihkan data sekali).</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 a <code class=\"docutils literal notranslate\">CharField</code>), but you want a\nformfield-specific piece of validation and, possibly, cleaning/normalizing\nthe 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=\"/id/5.0/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=\"/id/5.0/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=\"/id/5.0/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=\"/id/5.0/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=\"/id/5.0/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>Contoh dari setiap cara ini disediakan dibawah.</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>Membangkitkan <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>Untuk membuat pesan-pesan kesalahan lebih elastis dan mudah ditimpa, pertimbangkan panduan berikut ini:</p>\n<ul>\n<li><p>Sediakan gambaran <code class=\"docutils literal notranslate\">code</code> kesalahan pada pembangun:</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=\"s2\">&quot;Invalid value&quot;</span><span class=\"p\">),</span> code<span class=\"o\">=</span><span class=\"s2\">&quot;invalid&quot;</span><span class=\"p\">)</span>\n\n<span class=\"c1\"># Bad</span>\nValidationError<span class=\"p\">(</span>_<span class=\"p\">(</span><span class=\"s2\">&quot;Invalid value&quot;</span><span class=\"p\">))</span>\n</code></pre></div>\n</li>\n<li><p>Don't coerce variables into the message; use placeholders and the <code class=\"docutils literal notranslate\">params</code>\nargument of the constructor:</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=\"s2\">&quot;Invalid value: </span><span class=\"si\">%(value)s</span><span class=\"s2\">&quot;</span><span class=\"p\">),</span>\n    params<span class=\"o\">=</span><span class=\"p\">{</span><span class=\"s2\">&quot;value&quot;</span><span class=\"p\">:</span> <span class=\"s2\">&quot;42&quot;</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=\"s2\">&quot;Invalid value: </span><span class=\"si\">%s</span><span class=\"s2\">&quot;</span><span class=\"p\">)</span> <span class=\"o\">%</span> value<span class=\"p\">)</span>\n</code></pre></div>\n</li>\n<li><p>Menggunakan kunci-kunci pemetaan daripada pembentukan penempatan. Ini mengadakan menaruh variabel dalam pesanan apapun atau menghilangkan mereka saam sekali ketika menulis kembali pesan:</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=\"s2\">&quot;Invalid value: </span><span class=\"si\">%(value)s</span><span class=\"s2\">&quot;</span><span class=\"p\">),</span>\n    params<span class=\"o\">=</span><span class=\"p\">{</span><span class=\"s2\">&quot;value&quot;</span><span class=\"p\">:</span> <span class=\"s2\">&quot;42&quot;</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=\"s2\">&quot;Invalid value: </span><span class=\"si\">%s</span><span class=\"s2\">&quot;</span><span class=\"p\">),</span>\n    params<span class=\"o\">=</span><span class=\"p\">(</span><span class=\"s2\">&quot;42&quot;</span><span class=\"p\">,),</span>\n<span class=\"p\">)</span>\n</code></pre></div>\n</li>\n<li><p>Bungkus pesan dengan <code class=\"docutils literal notranslate\">gettext</code> untuk mengadakan terjemahan:</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=\"s2\">&quot;Invalid value&quot;</span><span class=\"p\">))</span>\n\n<span class=\"c1\"># Bad</span>\nValidationError<span class=\"p\">(</span><span class=\"s2\">&quot;Invalid value&quot;</span><span class=\"p\">)</span>\n</code></pre></div>\n</li>\n</ul>\n<p>Menaruh semua bersama:</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=\"s2\">&quot;Invalid value: </span><span class=\"si\">%(value)s</span><span class=\"s2\">&quot;</span><span class=\"p\">),</span>\n    code<span class=\"o\">=</span><span class=\"s2\">&quot;invalid&quot;</span><span class=\"p\">,</span>\n    params<span class=\"o\">=</span><span class=\"p\">{</span><span class=\"s2\">&quot;value&quot;</span><span class=\"p\">:</span> <span class=\"s2\">&quot;42&quot;</span><span class=\"p\">},</span>\n<span class=\"p\">)</span>\n</code></pre></div>\n<p>Mengikuti panduan ini terutama jika anda menulis formulir digunakan kembali, bidang formulir, dan bidang model.</p>\n<p>While not recommended, if you are at the end of the validation chain\n(i.e. your form <code class=\"docutils literal notranslate\">clean()</code> method) and you know you will <em>never</em> need\nto override your error message you can still opt for the less verbose:</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=\"s2\">&quot;Invalid value: </span><span class=\"si\">%s</span><span class=\"s2\">&quot;</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=\"/id/5.0/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=\"/id/5.0/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>Membangkitkan banyak kesalahan<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>Jika anda mengenali banyak kesalahan selama metode pembersihan dan berharap mensinyalkan semua dari mereka ke pengaju formulir, itu memungkinkan melewatkan daftar ke pembangun <code class=\"docutils literal notranslate\">ValidationError</code>.</p>\n<p>Seperti diatas, itu dianjutkan melewatkan daftar dari instance <code class=\"docutils literal notranslate\">ValidationError</code> dengan <code class=\"docutils literal notranslate\">code</code> dan <code class=\"docutils literal notranslate\">params</code> tetapi sebuah daftar string juga akan bekerja:</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    <span class=\"p\">[</span>\n        ValidationError<span class=\"p\">(</span>_<span class=\"p\">(</span><span class=\"s2\">&quot;Error 1&quot;</span><span class=\"p\">),</span> code<span class=\"o\">=</span><span class=\"s2\">&quot;error1&quot;</span><span class=\"p\">),</span>\n        ValidationError<span class=\"p\">(</span>_<span class=\"p\">(</span><span class=\"s2\">&quot;Error 2&quot;</span><span class=\"p\">),</span> code<span class=\"o\">=</span><span class=\"s2\">&quot;error2&quot;</span><span class=\"p\">),</span>\n    <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>\n        _<span class=\"p\">(</span><span class=\"s2\">&quot;Error 1&quot;</span><span class=\"p\">),</span>\n        _<span class=\"p\">(</span><span class=\"s2\">&quot;Error 2&quot;</span><span class=\"p\">),</span>\n    <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>Menggunakan pengesahan dalam praktik<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>The previous sections explained how validation works in general for forms.\nSince it can sometimes be easier to put things into place by seeing each\nfeature in use, here are a series of small examples that use each of the\nprevious features.</p>\n<section id=\"using-validators\">\n<span id=\"validators\"></span><h3>Menggunakan pengesah<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's form (and model) fields support use of utility functions and classes\nknown as validators. A validator is a callable object or function that takes a\nvalue and returns nothing if the value is valid or raises a\n<a class=\"reference internal\" href=\"/id/5.0/ref/exceptions/#django.core.exceptions.ValidationError\" title=\"django.core.exceptions.ValidationError\"><code class=\"xref py py-exc docutils literal notranslate\">ValidationError</code></a> if not. These can be passed to a\nfield's constructor, via the field's <code class=\"docutils literal notranslate\">validators</code> argument, or defined on the\n<a class=\"reference internal\" href=\"/id/5.0/ref/forms/fields/#django.forms.Field\" title=\"django.forms.Field\"><code class=\"xref py py-class docutils literal notranslate\">Field</code></a> class itself with the <code class=\"docutils literal notranslate\">default_validators</code>\nattribute.</p>\n<p>Validators can be used to validate values inside the field, let's have a look\nat Django's <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.core</span> <span class=\"kn\">import</span> validators\n<span class=\"kn\">from</span> <span class=\"nn\">django.forms</span> <span class=\"kn\">import</span> CharField\n\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>As you can see, <code class=\"docutils literal notranslate\">SlugField</code> is a <code class=\"docutils literal notranslate\">CharField</code> with a customized validator\nthat validates that submitted text obeys to some character rules. This can also\nbe done on field definition 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>slug <span class=\"o\">=</span> forms<span class=\"o\">.</span>SlugField<span class=\"p\">()</span>\n</code></pre></div>\n<p>setara pada:</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>Kasus-kasus umum seperti pengesahan terhadap sebuah surel atau sebuah regular expression dapat ditangani menggunakan kelas-kelas pengesah yang ada tersedia di Django. Sebagai contoh, <code class=\"docutils literal notranslate\">validators.validate_slug</code> adalah sebuah contoh dari <a class=\"reference internal\" href=\"/id/5.0/ref/validators/#django.core.validators.RegexValidator\" title=\"django.core.validators.RegexValidator\"><code class=\"xref py py-class docutils literal notranslate\">RegexValidator</code></a> dibangun dengan argumen pertama menjadi pola: <code class=\"docutils literal notranslate\">^[-a-zA-Z0-9_]+$</code>. Lihat bagian pada  <a class=\"reference internal\" href=\"/id/5.0/ref/validators/\"><span class=\"doc\">writing validators</span></a> untuk melihat daftar dari apa yang tersedia dan untuk sebuah contoh dari bagaimana menulis sebuah pengesah.</p>\n</section>\n<section id=\"form-field-default-cleaning\">\n<h3>Pembersihan awalan bidang formulir<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\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=\"s2\">&quot;,&quot;</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><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 <code class=\"docutils literal notranslate\">ContactForm</code> to demonstrate how you'd use this field:</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>Use <code class=\"docutils literal notranslate\">MultiEmailField</code> like any other form field. When the <code class=\"docutils literal notranslate\">is_valid()</code>\nmethod is called on the form, the <code class=\"docutils literal notranslate\">MultiEmailField.clean()</code> method will be\nrun as part of the cleaning process and it will, in turn, call the custom\n<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>Membersihkan atribut bidang khusus<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<span class=\"kn\">from</span> <span class=\"nn\">django.core.exceptions</span> <span class=\"kn\">import</span> ValidationError\n\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=\"s2\">&quot;recipients&quot;</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> 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>Membersihkan dan memeriksa bidang yang tergantung satu sama lain<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=\"/id/5.0/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<span class=\"kn\">from</span> <span class=\"nn\">django.core.exceptions</span> <span class=\"kn\">import</span> ValidationError\n\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><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> ValidationError<span class=\"p\">(</span>\n                    <span class=\"s2\">&quot;Did not send for &#39;help&#39; in the subject despite 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. Such\nerrors are non-field errors, which are displayed in the template with\n<code class=\"docutils literal notranslate\">{{ form.non_field_errors }}</code>.</p>\n<p>The call to <code class=\"docutils literal notranslate\">super().clean()</code> in the example code ensures that any validation\nlogic in parent classes is maintained. If your form inherits another that\ndoesn't return a <code class=\"docutils literal notranslate\">cleaned_data</code> dictionary in its <code class=\"docutils literal notranslate\">clean()</code> method (doing\nso is optional), then don't assign <code class=\"docutils literal notranslate\">cleaned_data</code> to the result of the\n<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><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\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><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=\"s2\">&quot;cc_myself&quot;</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=\"s2\">&quot;subject&quot;</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 string, or preferably an\ninstance of <code class=\"docutils literal notranslate\">ValidationError</code>. See <a class=\"reference internal\" href=\"#raising-validation-error\"><span class=\"std std-ref\">Membangkitkan ValidationError</span></a> for more\ndetails. Note that <code class=\"docutils literal notranslate\">add_error()</code> automatically removes the field from\n<code class=\"docutils literal notranslate\">cleaned_data</code>.</p>\n</section>\n</section>","rootId":"form-and-field-validation","toc":[{"title":"Membangkitkan ValidationError","anchor":"raising-validationerror","children":[{"title":"Membangkitkan banyak kesalahan","anchor":"raising-multiple-errors","children":[]}]},{"title":"Menggunakan pengesahan dalam praktik","anchor":"using-validation-in-practice","children":[{"title":"Menggunakan pengesah","anchor":"using-validators","children":[]},{"title":"Pembersihan awalan bidang formulir","anchor":"form-field-default-cleaning","children":[]},{"title":"Membersihkan atribut bidang khusus","anchor":"cleaning-a-specific-field-attribute","children":[]},{"title":"Membersihkan dan memeriksa bidang yang tergantung satu sama lain","anchor":"cleaning-and-validating-fields-that-depend-on-each-other","children":[]}]}],"breadcrumbs":[{"docname":"ref/index","title":"Acuan API","url":"/id/5.0/ref/"},{"docname":"ref/forms/index","title":"Formulir","url":"/id/5.0/ref/forms/"}],"prev":{"docname":"ref/forms/widgets","title":"Widget","url":"/id/5.0/ref/forms/widgets/"},"next":{"docname":"ref/logging","title":"Pencatatan","url":"/id/5.0/ref/logging/"},"formats":{"html":"/id/5.0/ref/forms/validation/","markdown":"/id/5.0/ref/forms/validation.md","json":"/id/5.0/ref/forms/validation.json"},"source":"https://github.com/django/django/blob/stable/5.0.x/docs/ref/forms/validation.txt","official":"https://docs.djangoproject.com/id/5.0/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","zh-hans","fr","ja","id","it","pt-br","ko","es","el","pl"]}