Magento2 Form Validation with example

Magento2 Form Validation with example

In this post we will show you Magento2 Form Validation, hear for Magento2 Form Validation we will give you demo and example for implement.

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 for Magento 2 Form Validation

<!-- form tag -->
<form class="form" id="custom-form-id" method="post" autocomplete="off">
   <fieldset class="fieldset">
       <legend class="legend"><span><?php echo __('User Personal Information') ?></span></legend><br>
        <div class="field required">
			<!-- form field -->
            <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>
   <!-- submit button -->
   <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 for Magento2 Form Validation

<!-- enable javascript validation for custom-form-id -->
<script type="text/x-magento-init">
    {
        "#custom-form-id": {
            "validation": {}
        }
    }
</script>

or

we can directly do it in html like this

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

or

<script type="text/javascript">
require([
    'jquery',
    'mage/mage'
], function($){ 
   var dataForm = $('#custom-form-id');
   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 info.

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

Hope this code and post will helped you for implement Magento2 Form Validation. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve onlincode. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs onlincode.org

Leave a Comment

Your email address will not be published. Required fields are marked *

1  +  6  =  

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US