Form API Ajax trigger callback with size of input I use the API Form of Drupal 8 to create my form.
I had an ajax callback on a field:

$form['association']['numero'] = array(
        '#type' =&gt; 'textfield',
        '#title' =&gt; t('foo'),
        '#size' =&gt; 10,
        '#maxlength' =&gt; 10,
        '#suffix' =&gt; '&lt;div id="ajax_error"&gt;&lt;/div&gt;',
        '#ajax' =&gt; [
            'callback' =&gt; '::fetchApiData',
            'event' =&gt; 'change',
            'prevent' =&gt; 'click',
        ],
    );


with my callback function :

public function fetchApiData(array $form, FormStateInterface $form_state)
{
    return 'foo';
}


It's all working fine, but i want to trigger the callback when the user writes 10 characters precisely. Does anyone has a solution for that?
You can do this:

1) Decide on an event name. In this code, the event name will be 'overminlength'

2) In the form element being defined using the Form API, set your #ajax as normal, but set the #ajax 'event' to the event name chosen in step 1:

'#ajax' =&gt; [
  'wrapper' =&gt; 'some_wrapper',
  'callback' =&gt; 'some_callback',
  // Set the custom event here:
  'event' =&gt; 'overminlength',
],


3) Create a custom JS file and attach it to the field

'#attached' =&gt; [
  'library' =&gt; ['mymdodule/mylibrary'],
],


4) Add a $.keyup() listener to the field.


In the callback, count the number of characters in the field
If it's more than X characters, call $.trigger(), and trigger the event from step 1

(function($, Drupal) {

  "use strict";

  function fieldwatcher(context) {
    $(context).find("#edit-myfield").once("fieldwatcher").each(function() {
      $(this).keyup(function() {
        // Change '3' to the number of characters after which you want to
        // trigger the ajax.
        if ($(this).val().length &gt; 3) {
          $(this).trigger("overminlength");
        }
      });
    });
  }

  Drupal.behaviors.testScript = {
    attach: function(context) {
      fieldwatcher(context);
    }
  };

}(jQuery, Drupal));