Magento2 – Form Validation

In this blog post we will see how to do form validation in magento2

There are different ways to use form validation let see the different ways.

First we will setup a test form

<form 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>

The data-validate is the attribute for validation.

To enable javascript validation

<script type="text/x-magento-init">
    {
        "#custom-form": {
            "validation": {}
        }
    }
</script>

or

we can directly do it in html like this

<form data-mage-init='{"validation": {}}' class="form" id="custom-form" method="post" autocomplete="off">

or

<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

here you can see different types of validation which can be used like ‘validate-cc-cvn’, ‘validate-length’,’validate-one-required’ etc etc

also the widget “$.widget(“mage.validation”)” is defined there for which you can see the options.