如何在Magento 2中验证自定义模块的表单

时间:2016-11-03 08:04:10

标签: forms validation magento2

我正在为magento 2中的用户详细信息创建简单的自定义模块。它具有三个文件的格式。我想在提交之前验证该数据。如何在magento 2中实现这一点?默认的magento验证器不像data-validate = {} ......我是否必须添加任何其他js文件进行验证?

helloworld.phtml文件

<form class="form create account form-create-account"   action="<?php echo $block->getFormAction() ?>" method="post" enctype="multipart/form-data"  data-mage-init='{"validation":{}}'>
    <fieldset class="fieldset create account" data-hasrequired="<?php /* @escapeNotVerified */ echo __('* Required Fields') ?>">
        <legend class="legend"><span><?php /* @escapeNotVerified */ echo __('Customer Information') ?></span></legend><br>
        <div class="field required">
            <label for="email_address" class="label"><span><?php /* @escapeNotVerified */ echo __('Email') ?></span></label>
            <div class="control">
                <input type="email" name="email" autocomplete="email" id="email_address" value="" title="<?php /* @escapeNotVerified */ echo __('Email') ?>" class="input-text" data-validate="{required:true, 'validate-email':true}">
            </div>
        </div>

        <div class="field required">
            <label for="First_Name" class="label"><span><?php /* @escapeNotVerified */ echo __('FirstName') ?></span></label>
            <div class="control">
                <input type="text" name="firstname"  id="first" value="" title="<?php /* @escapeNotVerified */ echo __('Email') ?>" class="input-text" data-validate="{required:true}" >
            </div>
        </div>

        <div class="field required">
            <label  class="label"><span><?php /* @escapeNotVerified */ echo __('LastName') ?></span></label>
            <div class="control">
                <input type="text" name="lastname"  id="first" value="" title="<?php /* @escapeNotVerified */ echo __('LastName') ?>" class="input-text" >
            </div>
        </div>

        <button type="submit" class="action submit primary" <span><?php /* @escapeNotVerified */ echo __('Submit') ?></span></button>

</form>

2 个答案:

答案 0 :(得分:3)

下面的验证代码,要在代码下方使用,您必须在表单中添加id,并在{j}代码中使用id

<script type="text/javascript">
require([
    'jquery',
    'mage/mage'
], function($){

   var dataForm = $('#custom-form');
   dataForm.mage('validation', {});

});
</script>

javascript库的验证定义为

lib/web/mage/validation.js

答案 1 :(得分:0)

关于验证,在Magento中,我需要对表单输入元素进行远程验证,例如输入用户名并在提交表单之前验证此字段以检查此用户名是否存在?我已经实现了这种方式......有没有更好的建议?

magento-jquery-remote-validation