2016-11-03 35 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

相關問題