How To Add Custom Validate Field In Magento 2 Form?

how to add custom validate field in magento 2 form

In today blog post, we will show you three easy-to-follow steps to add a custom validate field in your Magento 2 form. Let’s get started!

Step 1: Add Custom Validate Method

First, in the data-mage-init attribute, you must add a custom method named tigrenValidateMethod.

<form class=”form contact”
action=”<?= $block->escapeUrl($block->getFormAction()) ?>”
data-hasrequired=”<?= $block->escapeHtmlAttr(__(‘* Required Fields’)) ?>”

Then, you must add your custom field into the form:

	<div class="field name required">
            <label class="label" for="field_tigren"><span>Field Tigren Test(Tigren)</span></label>
            <div class="control">
                <input name="field_tigren" id="field_tigren" value="" class="input-text required tigren" type="text"/>

Here we’ve just added a class named tigren to validate field.

Step 2: Bind Custom Validation Method Name To A Javascript File By Using RequireJs

	var config = {
	    map: {
		"*": {
		    tigrenValidateMethod: "js/tigrenValidateField"

Step 3: Create Javascript File To Confirm Validate

	], function($){
	    'use strict';
	    return function() {

		    function(value, element) {
		        return this.optional(element) || /^Tigren/.test(value);
		    $.mage.__("Type 'Tigren' in this field.")

Those are three simple steps to add the custom validate field into Magento 2 form. Hope you find it useful and see you in the next tutorial!

More custom function tutorials in Magento 2 that you might be interested in:

One thought on “How To Add Custom Validate Field In Magento 2 Form?

  1. Alex says:

    Hello and thanks for your tutorial! When adding a custom field validation the according rule is triggered immediately when starting to type anthing into the field. Is there a way to trigger the validation after leaving the field or after submitting the form? For example:

    In checkout shipping step I want the STREET field to be checked for a number (to make sure the field contains the street name as well as the house number). Currently, when entering the first letter into this field the message “Please enter a house number” appears. This does not really make sense. The message shall appear after leaving the field without having entered a number, or after clicking on the button to the next checkout step.

    Is there a way to achieve this? Any hint would be very welcome. Thanks a lot!


Leave a Reply

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