SimpleMagento - Magento tutorials, tips and discussions with simplicity in mind
  • Magento 2
  • Frontend
  • Dev Talk
  • Checkout
  • UI components
  • Online Marketing
  • eCommerce Talk
  • Magento 2
  • Frontend
  • Dev Talk
  • Checkout
  • UI components
  • Online Marketing
  • eCommerce Talk
SimpleMagento - Magento tutorials, tips and discussions with simplicity in mind
No Result
View All Result
Home Frontend

Moving the validation error message, this time globally

by freelancer
March 25, 2022
0 0
Share on FacebookShare on Twitter

There is a proverb, “Life is full of surprises”. I would like to add, so is Magento 2. 😀

While trying some things out on the newsletter form, I noticed it would be great to change the position of the error message on the newsletter email field. I made another custom element #custom-newsletter-error in app/design/frontend/YOUR_VENDOR/YOUR_THEME/Magento_Newsletter/Templates/subscribe.phtml that should contain the error message…

<div class="block newsletter">
    ...
    <p id="custom-newsletter-error"><?= $block->escapeHtml('Newsletter error should appear here.') ?></p>
    ...
    <input name="email" type="email" id="newsletter"
           placeholder="<?= $block->escapeHtmlAttr(__('Enter your email address')) ?>"
           data-mage-init='{"mage/trim-input":{}}'
           data-validate="{required:true, 'validate-email':true}"
           data-errors-message-box="#custom-newsletter-error"
    />
    ...
</div>

However, the error message still appears in the default place, after the input field.

This means, there must be something specific on the product page, which makes it work in A2C section, but not elsewhere. In other words, it’s time to start digging through the code. After spending some finding what is where and putting all the pieces of the puzzle together, I was able to identify why it worked on product page only.

It is not nice to point fingers, but…. grouped product.

First thing that caught my attention was the custom data-errors-message-box attribute, which I thought had something to do with it. By searching the vendor/magento folder, the string was used in the following files:

  1. vendor/magento/module-catalog/view/frontend/web/product/view/validation.js
  2. vendor/magento/module-grouped-product/view/frontend/templates/product/view/type/grouped.phtml

Ok, so grouped product has the custom  <div id="validation-message-box"></div>, but I need to know where and how is the JavaScript file loaded on the page. After some additional search in the modules files, I found that it’s used as a RequireJS dependency in  vendor/magento/module-catalog/view/frontend/web/js/validate-product.js

define([
    'jquery',
    'mage/mage',
    'Magento_Catalog/product/view/validation',
    'catalogAddToCart'
], function ($) {
    ...
});

Which is loaded in vendor/magento/module-catalog/view/frontend/templates/product/view/addtocart.phtml

...
<script type="text/x-magento-init">
    {
        "#product_addtocart_form": {
            "Magento_Catalog/js/validate-product": {}
        }
    }
</script>

Improve the validation method!

With all the key information at hand, it is possible now to enhance the native validation process and provide this feature globally. First of all, create app/design/frontend/YOUR_VENDOR/YOUR_THEME/requirejs-config.js file and setup a mixin of main validation file:

var config = {
    config: {
        mixins: {
            'mage/validation': {
                'mage/validation-mixin': true
            },
        }
    }
};

Next logical step is to create the app/design/frontend/YOUR_VENDOR/YOUR_THEME/web/mage/validation-mixin.js , which will override the native options errorPlacement keh  with the following content (actual modification is wrapped with comment, see snippet below):

define([
    'jquery',
    'jquery-ui-modules/widget'
], function ($) {
    'use strict';
 
    var enhancedMageValidation = {
        /**
         * @param {*} error
         * @param {*} element
         */
        options: {
            errorPlacement: function (error, element) {
                var errorPlacement = element,
                    fieldWrapper,
                    messageBox;
 
                /* added snippet - start */
                // use custom element to display error message
                if (element.attr('data-errors-message-box')) {
                    messageBox = $(element.attr('data-errors-message-box'));
                    messageBox.html(error);
 
                    return;
                }
                /* added snippet - end */
 
                // logic for date-picker error placement
                if (element.hasClass('_has-datepicker')) {
                    errorPlacement = element.siblings('button');
                }
                // logic for field wrapper
                fieldWrapper = element.closest('.addon');
 
                if (fieldWrapper.length) {
                    errorPlacement = fieldWrapper.after(error);
                }
                //logic for checkboxes/radio
                if (element.is(':checkbox') || element.is(':radio')) {
                    errorPlacement = element.parents('.control').children().last();
 
                    //fallback if group does not have .control parent
                    if (!errorPlacement.length) {
                        errorPlacement = element.siblings('label').last();
                    }
                }
                //logic for control with tooltip
                if (element.siblings('.tooltip').length) {
                    errorPlacement = element.siblings('.tooltip');
                }
                //logic for select with tooltip in after element
                if (element.next().find('.tooltip').length) {
                    errorPlacement = element.next();
                }
                errorPlacement.after(error);
            }
        }
    }
 
    return function (mageValidation) {
        $.widget('mage.validation', mageValidation, enhancedMageValidation);
 
        return $.mage.validation;
    }
});

Now, if you refresh the page, the validation of newsletter email field should be placed into the configured HTML element

And there you have it! 🙂 You should now be able to customize where the error message will be displayed on any page on any field.

To test this, I tried to make something very silly – to set the email error on H1 tag on Forgot Password page located in app/design/frontend/YOUR_VENDOR/YOUR_THEME/Magento_Customer/templates/form/forgotpassword.phtml file with the following change:

<form class="form password forget"
      action="<?= $block->escapeUrl($block->getUrl('*/*/forgotpasswordpost')) ?>"
      method="post"
      id="form-validate"
      data-mage-init='{"validation":{}}'>
    ...
    <input
        type="email"
        name="email"
        alt="email"
        id="email_address"
        class="input-text"
        value="<?= $block->escapeHtmlAttr($block->getEmailValue()) ?>"
        data-mage-init='{"mage/trim-input":{}}'
        data-validate="{required:true, 'validate-email':true}"
        data-errors-message-box="h1 span"
    />
</form>

This is how it looks like before submitting the form:

And this is how it looks like when submitting the form:

Tags: FrontendDev TalkMagento 2
Previous Post

The true mystery of the world is the visible

Next Post

Add static content in Magento Checkout address form

freelancer

freelancer

Related Posts

Magento 2

Implementing payment gateway in Magento 2 – Sample 1

April 22, 2022
Magento 2

Implementing payment gateway in Magento 2 Spinned – Sample 1

April 22, 2022
Magento 2 Payment

Implementing payment gateway in Magento 2 – Sample 1

April 22, 2022
Magento 2

Routing in Magento 2 – Sample 1

April 22, 2022
MVC Magento 2

Magento 2 Controllers – Sample 1

April 22, 2022
Magento 2

How to create a basic module in Magento 2 – Sample 1

April 22, 2022

Leave a Reply Cancel reply

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

Categories

  • Administration
  • Search
  • Configuration
  • Starting Up
  • Extensions
  • News
  • PWA
  • Magento 2 API
  • Programming
  • MVC Magento 2
  • UX/UI Design
  • Shipping Magento 2
  • Database
  • Magento 2 Payment
  • Magento 2
  • Cache
  • Frontend
  • Integration
  • Dev Talk
  • Life at Inchoo
  • Checkout
  • Tips
  • UI components
  • Products
  • Online Marketing
  • Debugging
  • Magento
  • Search Magento 2
  • Upgrading Magento 2
  • Marketing
  • eCommerce Talk
  • Events & Observers
  • Uncategorized

Popular Post

Magento 2

Magento 2 frontend architecture – Sample 1

April 22, 2022
Magento 2

Magento 2 Luma Theme Under The Scope

March 27, 2022
Magento 2 Payment

Implementing payment gateway in Magento 2 – Sample 1

April 22, 2022
Frontend

Moving the validation error message, this time globally

March 25, 2022
No Result
View All Result
[vc_row full_width="stretch_row" vc_row_background="" css=".vc_custom_1516082354216{margin-top: 30px !important;padding-top: 22px !important;padding-bottom: 22px !important;}"][vc_column el_class=".footer_center" offset="vc_col-lg-offset-3 vc_col-lg-6"]
[vc_empty_space height="15px"][vc_column_text css=".vc_custom_1516083863519{margin-bottom: 0px !important;}" el_class=".copyright"]Copyright © 2018 JNews. Photography Blog theme by Jegtheme.[/vc_column_text][/vc_column][/vc_row]
No Result
View All Result
  • Magento 2
  • Frontend
  • Dev Talk
  • Checkout
  • UI components
  • Online Marketing
  • eCommerce Talk

© 2023 JNews - Premium WordPress news & magazine theme by Jegtheme.

Welcome Back!

Login to your account below

Forgotten Password?

Retrieve your password

Please enter your username or email address to reset your password.

Log In