How to Add a Custom Validate Field In Magento 2 Form?

Today, we’re going to teach you guys how to add a custom validate field in Magento 2.

In an eCommerce business, it is critical to check any data that you receive from your customers and make sure they’ve entered the correct input.

And in this post, we’re going to show you exactly how to add a custom validate field in any form of your Magento 2 store & verify customers’ data.

Steps to Add a Custom Validate Field In Magento 2 Form

Please follow the below steps to add a custom validate field in your Magento 2 form.

Step - 1

First of all, you need to add a custom method named MDValidateMethod in the data-mage-init attribute and paste the following code:

<form class=”form contact”

action=”<?= $block->escapeUrl($block->getFormAction()) ?>”

id=”contact-form”

method=”post”

data-hasrequired=”<?= $block->escapeHtmlAttr(__(‘* Required Fields’)) ?>”

data-mage-init='{

“validation”:{},

“MDValidateMethod”:{}

}’>

Step - 2

After that, you need to add a custom field in your Magento 2 form with the following code:

<div class=”field name required”>

<label class=”label” for=”field_MD”><span>Field MD Test(MageDelight)</span></label>

<div class=”control”>

<input name=”field_MD” id=”field+MD” value=””class” input-text required MD” type=”text”/>

</div>

</div>

Step - 3

Next, we now need to bind the custom validation method name to a JavaScript file via RequireJS.

app/design/frontend/MageDelight/magedelight/requirejs-config.js

Var config = {

Map: {

  “*”: {

MDValidateMethod: “js/MagedelightValidateField”

}

}

};

Step - 4

Now, we need to create a JavaScript file to confirm validate with the following code:

app/design/frontend/MageDelight/magedelight/web/js/MageDelightValidateField.js

define([

‘Jquery’,

‘jquery/ui’,

‘jquery/validate’,

‘mage/translate’

], function($){

‘Use strict’;

Return function() {

$.validator.addMethod(

“Magedelight”,

function(value, element) {

      Return this.optional(element) || /^Magedelight/.test(value);

},

$.mage._(“Type ‘MageDelight’ in this field.”)

);

}

});

Conclusion

And that’s about it!

This is the easiest way to add a custom validate field in any form of your store.

And if you need our professional assistance, feel free to contact us anytime.