Running a Magento 2 website can sometimes feel like assembling a jigsaw puzzle – every piece needs to fit just right. One tricky piece that often stumps folks is the ‘Form Validation’ – specifically, adding a custom validate field.
But fear not!
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!
Contents
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()) ?>”
id=”contact-form”
method=”post”
data-hasrequired=”<?= $block->escapeHtmlAttr(__(‘* Required Fields’)) ?>”
data-mage-init='{
“validation”:{},
“tigrenValidateMethod”:{}
}’>
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"/> </div> </div>
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
app/design/frontend/Tigren/tigren/requirejs-config.js var config = { map: { "*": { tigrenValidateMethod: "js/tigrenValidateField" } } };
Step 3: Create Javascript File To Confirm Validate
app/design/frontend/Tigren/tigren/web/js/tigrenValidateField.js define([ 'jquery', 'jquery/ui', 'jquery/validate', 'mage/translate' ], function($){ 'use strict'; return function() { $.validator.addMethod( "tigren", 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. We hope that this post has been helpful to you.
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!
Regards,
Alex
Hey Alex, feel free to email us your question, as it would be quite lengthy to answer your question here. All the best!