Magento2 添加自定义表单验证规则

2020年8月18日 浏览量 37 2 min read
Magento2 添加自定义表单验证规则

本篇博客是Magento2 验证自定义表单的后续内容,它逐步解释了验证表单所需的内容。

但是,如果必须实现另一个字段,而该字段必须采用特定格式或者这种规则甚至不存在,该怎么办呢

我们将处理一个位于自定义主题中的联系表单(在本例中为Magease/FormValidation):

app/design/frontend/Magease/FormValidation/Magento_Contact/templates/form.phtml

  1. 添加自定义验证方法
    data-mage-init属性中,添加自定义方法(在本例中为theMageaseValidationMethod),它将用于触发我们的自定义验证规则:
    <form class="form contact"
          action="<?php /* @escapeNotVerified */ echo $block->getFormAction(); ?>"
          id="contact-form"
          method="post"
          data-hasrequired="<?php /* @escapeNotVerified */ echo __('* Required Fields') ?>"
          data-mage-init='{
    	"validation":{},
    	 "theMageaseValidationMethod":{}
    }'>
  2. 在同一表单中,添加自定义字段:
    <form>
    <!-- form content -->
     
    <div class="field name required">
                <label class="label" for="field5"><span>Field 5 (magease)</span></label>
                <div class="control">
                    <input name="field5" id="field5" title="Field 5" value="" class="input-text required magease" type="text"/>
                </div>
            </div>
     
    <!-- form content -->
     
    </form>

    如您所见,输入字段中添加了一个名为magease的自定义类,它将用作自定义规则名来验证该字段。

  3. 使用RequireJs(app/design/frontend/Magease/FormValidation/requirejs-config.js)将自定义验证方法名称绑定到Javascript文件:
    var config = {
        map: {
            "*": {
                theMageaseValidationMethod: "js/theMageaseValidationRule"
            }
        }
    };
  4. 使用验证字段的代码创建Javascript文件(app/design/frontend/Magease/FormValidation/web/js/theMageaseValidationRule.js):
    define([
        'jquery',
        'jquery/ui',
        'jquery/validate',
        'mage/translate'
    ], function($){
        'use strict';
     
        return function() {
            $.validator.addMethod(
                "magease",
                function(value, element) {
                    return this.optional(element) || /^Magease/.test(value);
                },
                $.mage.__("Type 'Magease' in this field")
            );
        }
    });

让我们打开浏览器并提交表单!

好的,我们可以看到验证工作正常,默认情况下,required规则首先开始。让我们输入内容并提交表单...

我们调用了自定义验证规则!现在如果我们输入“Magease”这个词并提交表格......

错误消息消失了,我们的自定义验证按预期工作!

Previous article:
Next article:
Comments
发表评论,留下你的足迹
我们不会公开你的邮箱地址

是否允许我们在发布新内容或者进行促销活动向您发送消息?

Remind me later

Thank you! Please check your email inbox to confirm.

Oops! Notifications are disabled.

© 2014-2023 www.magease.com. All Rights Reserved. 寰云网络 版权所有    鲁ICP备 14014975号-1