Magento 2 Form Validation


Today, I will explain to you about How many types of form validation which used in the fronted.

As per specific client requirement when you creating any custom form in the frontend via your custom module or theme so you need to make sure about without using any 3rd party validation tool, How can you do it using Magento 2 validation widget?

So, just check below 3 different ways to do form validation.

Assume that you already have custom from which have form id like “magento-expertise-form”.

Method 1: Accept javascript validation using the x-magento-init script.

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

Note: Just add above script after closing your tag and add your custom validation rule in between open and close parentheses i.e: {}

Method 2: Using HTML attribute.

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

Note: You can also apply the rule directly via HTML like the above example.

Method 3: Call validation using javascript.

<script type="text/javascript">
], function($){
	var dataForm = $('#magento-expertise-form');
	dataForm.mage('validation', {});

Note: same as the above 2 methods you also need to add your validation rule in dataForm.mage method.

As per Magento 2, validation library output comes from below location:

Thanks for reading this post!

About the author

I’m Magento Certified Developer having quite 5 years of commercial development expertise in Magento as well as in Shopify. I’ve worked primarily with the Magento and Shopify e-commerce platform, managing the complexities concerned in building e-commerce solutions tailored to a client’s specific desires.

Related Posts

2 Responses
  1. I have been surfing online more than 3 hours today, yet
    I never found any interesting article like yours. It’s pretty worth enough for me.
    In my opinion, if all web owners and bloggers made good content as
    you did, the internet will be a lot more useful than ever before.
    Thank you for the good writeup.

Leave a Reply