Jawaban:
Anda dapat menambahkan kelas untuk validasi di Magento 2. Lihat contoh di bawah. Ada hampir 72 aturan (kelas validasi) yang dapat Anda gunakan:
$fieldset->addField(
'email_from',
'text',
['name' => 'email_from', 'label' => __('Email From'), 'title' => __('Email From'), 'required' => true, 'class' => 'validate-email']
);
Lihat blog untuk daftar aturan yang tersedia untuk info lebih lanjut:
Berikut adalah daftar aturan kelas validasi yang didukung oleh magento 2. Anda hanya perlu menambahkan kelas css agar aturan dapat diterapkan.
min_text_length max_text_length max-words min-words range-words letters-with-basic-punc alphanumeric letters-only no-whitespace zip-range integer vinUS dateITA dateNL time time12h phoneUS phoneUK mobileUK stripped-min-length email2 url2 credit-card-types ipv4 ipv6 pattern validate-no-html-tags validate-select validate-no-empty validate-alphanum-with-spaces validate-data validate-street validate-phoneStrict validate-phoneLax validate-fax validate-email validate-emailSender validate-password validate-admin-password validate-url validate-clean-url validate-xml-identifier validate-ssn validate-zip-us validate-date-au validate-currency-dollar validate-not-negative-number validate-zero-or-greater validate-greater-than-zero validate-css-length validate-number validate-number-range validate-digits validate-digits-range validate-range validate-alpha validate-code validate-alphanum validate-date validate-identifier validate-zip-international validate-state less-than-equals-to greater-than-equals-to validate-emails validate-cc-number validate-cc-ukss required-entry checked not-negative-amount validate-per-page-value-list validate-new-password validate-item-quantity equalTo
Ada 3 cara berbeda untuk menggunakan validasi formulir di magento 2
Untuk mengaktifkan validasi javascript, gunakan kode berikut di templat Anda
<form class="form" id="custom-form" method="post" autocomplete="off">
<fieldset class="fieldset">
<legend class="legend"><span><?php echo __('Personal Information') ?></span></legend><br>
<div class="field required">
<label for="email_address" class="label"><span><?php echo __('Email') ?></span></label>
<div class="control">
<input type="email" name="email" id="email_address" value="" title="<?php echo __('Email') ?>" class="input-text" data-validate="{required:true, 'validate-email':true}">
</div>
</div>
</fieldset>
<div class="actions-toolbar">
<div class="primary">
<button type="submit" class="action submit primary" title="<?php echo __('Submit') ?>"><span><?php echo __('Submit') ?></span></button>
</div>
</div>
</form>
1
<script type="text/x-magento-init">
{
"#custom-form": {
"validation": {}
}
}
</script>
2
<form data-mage-init='{"validation": {}}' class="form" id="custom-form" method="post" autocomplete="off">
3
<script type="text/javascript">
require([
'jquery',
'mage/mage'
], function($){
var dataForm = $('#custom-form');
dataForm.mage('validation', {});
});
</script>
* custom-form adalah id formulir yang dapat Anda ganti dengan id formulir Anda
Daftar aturan validasi formulir
Untuk mengakhiri artikel ini, daftar nama aturan validasi disediakan di sini sebagai referensi cepat menuju dokumentasi resmi:
Aturan Magento:
validate-no-html-tags
validate-select
validate-no-empty
validate-alphanum-with-spaces
validate-data
validate-street
validate-phoneStrict
validate-phoneLax
validate-fax
validate-email
validate-emailSender
validate-password
validate-admin-password
validate-customer-password
validate-url
validate-clean-url
validate-xml-identifier
validate-ssn
validate-zip-us
validate-date-au
validate-currency-dollar
validate-not-negative-number
validate-zero-or-greater
validate-greater-than-zero
validate-css-length
validate-number
required-number
validate-number-range
validate-digits
validate-digits-range
validate-range
validate-alpha
validate-code
validate-alphanum
validate-date
validate-date-range
validate-cpassword
validate-identifier
validate-zip-international
validate-one-required
validate-state
required-file
validate-ajax-error
validate-optional-datetime
validate-required-datetime
validate-one-required-by-name
less-than-equals-to
greater-than-equals-to
validate-emails
validate-cc-type-select
validate-cc-number
validate-cc-type
validate-cc-exp
validate-cc-cvn
validate-cc-ukss
validate-length
required-entry
not-negative-amount
validate-per-page-value-list
validate-per-page-value
validate-new-password
required-if-not-specified
required-if-all-sku-empty-and-file-not-loaded
required-if-specified
required-number-if-specified
datetime-validation
required-text-swatch-entry
required-visual-swatch-entry
required-dropdown-attribute-entry
Validate-item-quantity
validate-grouped-qty
validate-one-checkbox-required-by-name
validate-date-between
validate-dob
max-words
min-words
range-words
letters-with-basic-punc
alphanumeric
letters-only
no-whitespace
zip-range
integer
vinUS
dateITA
dateNL
time
time12h
phoneUS
phoneUK
mobileUK
stripped-min-length
email2
url2
credit-card-types
ipv4
ipv6
pattern
allow-container-className
Aturan jQuery:
required,
remote,
email,
url,
date,
dateISO,
number,
digits,
creditcard,
equalTo,
maxlength,
minlength,
rangelength,
range,
max,
min
lihat http://inchoo.net/magento-2/validate-custom-form-in-magento-2/
Dalam komponen UI dapat digunakan dengan mengikuti konfigurasi sampel (Magento v2.2.0):
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
<fieldset name="general">
<field name="priority" sortOrder="1000" formElement="input">
<settings>
<validation>
<rule name="not-negative-amount" xsi:type="boolean">true</rule>
</validation>
[...]
</settings>
</field>
</fieldset>
</form>
Lihat lebih banyak contoh dalam file:
vendor/magento/module-cms/view/adminhtml/ui_component/cms_page_form.xml
Daftar validator di Komponen UI dapat ditemukan di vendor/magento/module-ui/view/base/web/js/lib/validation/rules.js
.
Baru saja menulis skrip ini untuk mengambil semua kunci dengan pesan kesalahan untuk penjelasan:
Naskah:
declare -A list
key=''
while IFS= read -r line; do
# echo "${line} -"
if [ -z "${key:-}" ]; then
# match validation key
match=$(echo "${line}" | grep -Eo "^ ['\"]([A-Za-z0-9-]|_)+" | tr -d "' ")
if [ -n "${match}" ]; then
key=${match}
fi
else
# match message
match=$(echo "${line}" | sed -rn "s|.*\\$\.mage\.__[(]['\"](.*)['\"][)].*|\1|p")
if [ -n "${match}" ]; then
list[${key}]=${match}
key=''
fi
fi
done < "${DOCROOT_DIR:-/var/www/html}/vendor/magento/module-ui/view/base/web/js/lib/validation/rules.js"
for i in "${!list[@]}"
do
printf "%s:\n %s\n" "${i}" "${list[$i]}"
done
Jika Anda mengambil referensi dari / pelanggan / akun / buat halaman, Anda dapat melihat potongan kode berikut di bawah formulir:
<script>
require([
'jquery',
'mage/mage'
], function($){
var dataForm = $('#form-validate');
var ignore = null;
dataForm.mage('validation', {
ignore: ignore ? ':hidden:not(' + ignore + ')' : ':hidden'
}).find('input:text').attr('autocomplete', 'off');
});
</script>
Dan jika Anda memeriksa atribut input formulir, Anda bisa melihat class
nilai atribut seperti Magento 1 bersama dengan data-validate
atribut baru . Ini bisa menjadi dasar untuk melangkah.
File kunci untuk Validasi:
Ketika menggunakan komponen UI untuk membuat formulir, kita bisa menggunakan validasi seperti di bawah ini, ini berfungsi di Magento 2.1.x, saya belum mengujinya di versi lain.
<field name="priority">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="dataType" xsi:type="string">text</item>
<item name="label" xsi:type="string" translate="true">Priority</item>
<item name="formElement" xsi:type="string">input</item>
<item name="source" xsi:type="string">module_name</item>
<item name="dataScope" xsi:type="string">priority</item>
<item name="validation" xsi:type="array">
<item name="required-entry" xsi:type="boolean">true</item>
<item name="validate-integer" xsi:type="boolean">true</item>
</item>
</item>
</argument>
</field>
Perhatikan item validasi , di dalamnya kita bisa menambahkan aturan validasi , seperti required-entry
, validate-integer
dll.
<item name="validation" xsi:type="array">
<item name="required-entry" xsi:type="boolean">true</item>
<item name="validate-integer" xsi:type="boolean">true</item>
<item name="validation_rule_name" xsi:type="boolean">true</item>
...
</item>
Semua aturan validasi dapat Anda temukan dalam file vendor/magento/module-ui/view/base/web/js/lib/validation/rules.js
, seperti validate-date
, validate-emails
dll.
Saya memiliki persyaratan yang sama untuk Validasi Formulir Magento2 dan saya melakukan kode ini
Pertama kita akan menyiapkan formulir tes
<!-- form tag -->
<form class="form" id="custom-form-id" method="post" autocomplete="off">
<fieldset class="fieldset">
<legend class="legend"><span><?php echo __('User Personal Information') ?></span></legend><br>
<div class="field required">
<!-- form field -->
<label for="email_address" class="label"><span><?php echo __('Email') ?></span></label>
<div class="control">
<input type="email" name="email" id="email_address" value="" title="<?php echo __('Email') ?>" class="input-text" data-validate="{required:true, 'validate-email':true}">
</div>
</div>
</fieldset>
<!-- submit button -->
<div class="actions-toolbar">
<div class="primary">
<button type="submit" class="action submit primary" title="<?php echo __('Submit') ?>"><span><?php echo __('Submit') ?></span></button>
</div>
</div>
</form>
Untuk mengaktifkan validasi javascript untuk Validasi Formulir Magento2
<!-- enable javascript validation for custom-form-id -->
<script type="text/x-magento-init">
{
"#custom-form-id": {
"validation": {}
}
}
</script>
Referensi :: http://www.onlinecode.org/magento2-form-validation-example/
Opsi "no-whitespace" tidak berfungsi dengan benar (setidaknya di Magento 2.1). Ini memicu pesan kesalahan pada semua jenis karakter "spasi". Nilai "test me" dan "test me" akan mengembalikan kesalahan yang sama.