2016-11-03 37 views
1

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

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> 
+0

你的代码看起来很完美,并检查它在这里工作,可能是你有问题,你的目录结构或布局的问题,你怎么有负载的布局文件这个模板? –

+0

是啊...它工作正常后,我在上面.phtml文件中添加此脚本.....

+0

您不需要在您的phtml文件中添加脚本,只需在表单中添加脚本 - data-hasrequired =“<?php/* @escapeNotVerified */echo __('*必填字段)>” 数据MAGE-的init =?‘{‘验证’:{}}’> –

回答

2

下面的验证代码,下面的代码使用必须添加在您的形式idid您需使用JavaScript代码的下方。

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

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

}); 
</script> 

JavaScript库进行验证被定义是

lib/web/mage/validation.js 
0

关于验证,在Magento,我需要形式输入元件的远程验证等输入用户名和提交表单,以检查之前验证该字段这个用户名是否存在?我已经实现了这种方式....有没有更好的建议?

magento-jquery-remote-validation

+0

这是好的方式,我认为这so.check核心文件MagentoRootDirectory /供应商/ Magento的/模块的客户/视图/前端/模板/表格/ register.phtml –

+0

谢谢很多@vijayb – Manish

相关问题