Skip to main content

Magento2 Form Validation

in this wiki we will provide a simple form with Validation that we can use in Magento2, hope this will be helpful for all readers

 

you can use the below code in phtml file

<form data-mage-init='{"validation": {}}' class="form" id="custom-form" method="post" autocomplete="off">
    <fieldset class="fieldset">
        <legend class="legend"><span><?php echo __('Personal Information') ?></span></legend><br>
        <div class="field required">
            <label for="email_address" class="label"><span><?php echo __('Email') ?></span></label>
            <div class="control">
                <input type="email" name="email" id="email_address" value="" title="<?php echo __('Email') ?>" class="input-text" data-validate="{required:true, 'validate-email':true}">
            </div>
        </div>
    </fieldset>
    <div class="actions-toolbar">
        <div class="primary">
            <button type="submit" class="action submit primary" title="<?php  echo __('Submit') ?>"><span><?php echo __('Submit') ?></span></button>
        </div>
    </div>
</form>

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

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

    });
</script>