Reputation: 469
I am creating simple custom module for user details in magento 2. It has form with three fileds. I want to validate the that data before I submit. How to achieve this in magento 2? Default magento validators are not working like data-validate={}... Do I have to add any additional js files for validation?
helloworld.phtml file
<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>
Upvotes: 1
Views: 7956
Reputation: 667
Regarding validation, in Magento, I need a remote validation for form input element like entering username and validate this field before submitting the form to check this username exist or not? I have implemented this way ....is there any better suggestion?
magento-jquery-remote-validation
Upvotes: 0
Reputation: 508
Below code for validation, for use below code you have to add id
in your form and that id
you need to use in below javascript code.
<script type="text/javascript">
require([
'jquery',
'mage/mage'
], function($){
var dataForm = $('#custom-form');
dataForm.mage('validation', {});
});
</script>
The javascript library were validation is defined is
lib/web/mage/validation.js
Upvotes: 4