Answers:
您可以在Magento 2中添加用于验证的类。请参见下面的示例。您可以使用将近72条规则(验证类):
$fieldset->addField(
'email_from',
'text',
['name' => 'email_from', 'label' => __('Email From'), 'title' => __('Email From'), 'required' => true, 'class' => 'validate-email']
);
有关更多信息,请参见博客以获取可用规则列表:
这是magento 2支持的验证类规则的列表。您只需添加css类即可应用该规则。
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
在magento 2中有3种不同的方式来使用表单验证
要启用javascript验证,请在模板中使用以下代码
<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>
*自定义表单是表单ID,您可以将其替换为表单ID
表单验证规则列表
为了总结本文,此处提供了验证规则名称列表,作为对官方文档的快速参考:
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
jQuery规则:
required,
remote,
email,
url,
date,
dateISO,
number,
digits,
creditcard,
equalTo,
maxlength,
minlength,
rangelength,
range,
max,
min
请参阅http://inchoo.net/magento-2/validate-custom-form-in-magento-2/
在UI组件中,可以通过以下示例配置(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>
查看文件中的更多示例:
vendor/magento/module-cms/view/adminhtml/ui_component/cms_page_form.xml
可在以下位置找到的UI组件中的验证器列表 vendor/magento/module-ui/view/base/web/js/lib/validation/rules.js
。
只需编写此脚本即可获取所有带有错误消息的键,以进行说明:
剧本:
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
如果您参考/ customer / account / create页面,则可以在表格下方看到以下代码:
<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>
并且,如果您检查表单的输入属性,则可以看到Magento 1,如class
属性值和新data-validate
属性。这可以作为加强的基础。
验证密钥文件:
当使用UI组件制作表单时,我们可以使用如下所示的验证,它可以在Magento 2.1.x中运行,我尚未在其他版本中对其进行测试。
<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>
注意验证项,在其中我们可以添加验证规则,如required-entry
,validate-integer
等等。
<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>
您可以在file中找到的所有验证规则vendor/magento/module-ui/view/base/web/js/lib/validation/rules.js
,例如validate-date
,validate-emails
等等。
我对Magento2表单验证具有相同的要求,并且我执行了此代码
首先,我们将设置测试表格
<!-- 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>
为Magento2表单验证启用JavaScript验证
<!-- enable javascript validation for custom-form-id -->
<script type="text/x-magento-init">
{
"#custom-form-id": {
"validation": {}
}
}
</script>
参考 :: http://www.onlinecode.org/magento2-form-validation-example/
“ no-whitespace”选项无法正常工作(至少在Magento 2.1上有效)。它会在任何类型的“空格”字符上触发错误消息。值“ test me”和“ test me”将返回相同的错误。