Custom validation message of input on Drupal 9

A new day - new Drupal tasks. 

We have a site on Drupal 9 version, where we need to add a data pattern for input type fields to enter only numbers in a certain pattern. 

Adding the template itself to the webform input field is not such a difficult task, but when it comes to the error message, it turns out that it is not possible to change its text through the webform. For this, we will use the jquery code.

So, for a regular static form, we create a scriptname.js file with approximately this content

(function ($, Drupal) {
    Drupal.behaviors.addInputAttributes = {
      attach: function (context, settings) {
        var input = document.getElementById('id_of_our_input');
       
        input.oninvalid = function(event) {
            event.target.setCustomValidity('Please enter the number in the format XXX-XX-XXXXX');
        }
      }
    };
  })(jQuery, Drupal);

But, if we need to change the error text of the field, which is in the popup, we need to modify our script a bit, because without it our script will not work, when it is loaded, it will not see the field with our ID and will simply give an error. So we make script.js

(function ($, Drupal) {
    Drupal.behaviors.addInputAttributes = {
      attach: function (context, settings) {
        $('button.info-button', context).once('addInputAttributes').on('click', function() {
          setTimeout(function() {
            var product_telinput = document.getElementById('id_of_our_input');
            if (product_telinput) {
              product_telinput.oninvalid = function(event) {
                event.target.setCustomValidity('Please enter the number in the format XXX-XX-XXXXX');
              };
            }
          }, 500);
        });
      }
    };
  })(jQuery, Drupal);

Here we first prescribe that everything that happens only after clicking on the buttons with the required class. We also add a timer, depending on the user's connection, the field with the required ID may not load as quickly as we would like, therefore, after pressing the button, a 500ms countdown starts, after which only our field is accessed.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
The comment language code.